using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LessokajiWeaverUtilities.Utilities;
using Newtonsoft.Json;
using SimpleLite.RCS;
using SimpleLite.RCS.CarTypes;
using SimpleCore;
using StandardScene.Model;

namespace StandardScene.Scheduler
{
    [MissionType(Name = "调度心跳进程",editor = typeof(HeartBeatMission))]
    [I18N.DocumentTranslation(Name = "Heart Beat Mission", locale = "en")]
    public class HeartBeatMission:Mission
    {
        [JsonIgnore] private bool _started = false;
        private Thread _myThread;
        private HttpClient _httpClient;

        public static Mission Create()
        {
            return new HeartBeatMission();
        }
        [MethodMember(Name = "启动进程", Description = "开始下发调度心跳")]
        public override void Execute()
        {
            if(_started) return;
            status.status = "已启动";
            int count = 0;
            _httpClient = new HttpClient();
            _myThread = new Thread(() =>
            {
                _started = true;
                while (_started)
                {
                    Thread.Sleep(1000);
                    count++;
                    status.status = $"已启动:{count}";
                    var carList = SimpleLib.GetAllCars();
                    foreach (var car in carList)
                    {
                        if (car is not GhostCar gCar || Commons.GetVehicleStatus(gCar)!= VehicleStatus.Normal) continue;
                        try
                        {
                            //((ClumsyCar)car).ImmediateCommand("pilot.SimpleSignal=1");
                            var ip = gCar.address;
                            _httpClient.GetStringAsync($"http://{ip}:8008/setValue?FieldName=SimpleSignal&Value=1");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"http error" + e.Message + e.StackTrace);
                        }
                    }
                }
            });
            _myThread.Start();
        }

        [MethodMember(Name = "关闭进程", Description = "停止下发心跳")]
        public void Stop()
        {
            _started = false;
            _myThread?.Join(2000);
            _myThread = null;
            status.status = "已关闭";
        }
    }
}
