using System;
using System.Linq;
using cAlgo.API;         // Required for ChartManager, ChartFrame, Chart, IChartRobot
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Plugins
{
    [Plugin(AccessRights = AccessRights.None)]
    public class MS_StartAllBots : Plugin
    {
        private const string TargetBotName = "MS_ExportTickData";

        protected override void OnStart()
        {
            // Access the static ChartManager to get all open chart frames.
            // ChartManager.ChartFrames returns an IReadOnlyList<ChartFrame>.
            //var chartFrames = ChartManager;
            
            // Iterate through each chart frame.
            foreach (var frame in ChartManager)
            {
                if( frame is ChartFrame )
                {
                    var chartFrame = frame as ChartFrame;
                
                    // Each ChartFrame has a Chart property.
                    var chart = chartFrame.Chart;
    
                    // It's good practice to ensure the chart object is not null.
                    if (chart != null)
                    {
                        // Access all cBot instances (IChartRobot) attached to the current chart.
                        // Chart.Robots returns an IReadOnlyList<IChartRobot>.
                        var chartRobots = chart.Robots;
                            
                        // Iterate through each cBot instance on the current chart.
                        foreach (var chartRobot in chartRobots)
                        {
                            // Check if the cBot's template name matches the target name
                            // and if the cBot instance is not currently running.
                            if (chartRobot.Name == TargetBotName)
                            {
                                RobotState state = chartRobot.State;
                                if( state == RobotState.Stopped )
                                {
                                    var ppath = chartRobot.Parameters.First( p => p.Name == "DirectoryName" );
                                    if( ppath != null )
                                    {
                                        ppath.Value = "\\\\COFFEE\\TickData\\Pepperstone";
                                        chartRobot.Start();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        protected override void OnStop()
        {
            // Handle Plugin stop here if needed.
        }
    }
}