using KYFramework;
using KYFramework.Network;
using Model;
using MongoDB.Bson;

namespace SimulationServer;

public class ZCRescueMission : Entity
{
    public string MissionId; // 任务ID
    public bool Success; // 任务是否成功
    public double InitArea;
    public double SimulationTime;
    public List<AircraftZC> AircraftZCs = new List<AircraftZC>();
    public void Start()
    {
        AircraftZCs?.ForEach(a => a.Start());
        var readyTime = AircraftZCs.First().TaskReadyTime;
        Log.Info("侦察时间延迟" + readyTime);
        Task.Delay(TimeSpan.FromSeconds(readyTime)).ContinueWith(t => this.StartAsyncZC());
    }
}

public static class ZCRescueMissionSystem
{
     /// <summary>
    /// 开始同步信息到客户端
    /// </summary>
    /// <param name="self"></param>
    public static void StartAsyncZC(this ZCRescueMission self)
    {
        foreach (var aircraft in self.AircraftZCs)
        {
            var location = FXJHGenerate.GetAllCurrentLocation(aircraft.TurningPoints, self.SimulationTime);
            
            // 同步信息到客户端
            self.SyncLocation(location.Item1, aircraft);
            
            if (location.Item2) // 判断飞机飞到终点
            {
                aircraft.SyncOver = true;
            }
        }
        
        // 如果 aircraft.SyncOver 为 true ,从列表一处当前aircraft
        self.AircraftZCs.RemoveAll(a => a.SyncOver);
        
        if (self.AircraftZCs.Count == 0)
        {
            // 任务结束
            S2C_StmulationEnd end = new S2C_StmulationEnd();
            SessionComponent.Instance.Session.Send(end);
            return;
        }
        
        self.SimulationTime += Init.SimulationSpeed;
        Task.Delay(TimeSpan.FromSeconds(1f)).ContinueWith(t => self.StartAsyncZC());
    }
    
    public static void SyncLocation(this ZCRescueMission self,CurrentLocation location,AircraftEntity aircraft)
    {
        // 同步信息到客户端
        if (location != null)
        {
            // 同步信息到客户端
            S2C_TurningPointOutput s2CTurningPointOutput = new S2C_TurningPointOutput();
            s2CTurningPointOutput.AircraftID = aircraft.AircraftId;
            //s2CTurningPointOutput.TurningPointName = fly.TurningPointName;

            s2CTurningPointOutput.PresentMission = location.PresentMission;
            
            s2CTurningPointOutput.PresentLocation = new Point
            {
                Altitude = location.CurrentHei,
                Latitude = location.CurrentLat,
                Longitude = location.CurrentLon
            };

            s2CTurningPointOutput.PresentVelocity = location.Currentvelo;
            SessionComponent.Instance.Session.Send(s2CTurningPointOutput); 
            Log.Info($"飞机{aircraft.Name} 当前位置: {location.ToJson()}");
        }
    }
}