using LessokajiWeaverUtilities.Utilities;
using LoopViewerApp;
using Newtonsoft.Json;
using SimpleLite.RCS;
using SimpleLite.RCS.CarTypes;
using SimpleCore;
using SimpleCore.PropType;
using SimpleCore.Traffic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace StandardScene.InterLock
{
    [MissionType(Name = "交通管制", editor = typeof(TrafficInterlockMission))]
    [I18N.DocumentTranslation(Name = "Traffic Mission", locale = "en")]
    public class TrafficInterlockMission : Mission
    {
        public static List<TrafficArea> TrafficAreaList {  get; set; } = new List<TrafficArea>();

        public TrafficInterlockMission()
        {
            TrafficControl.BeforeLock += (car, siteId) =>
            {
                return EnterArea(car, siteId);
            };

            TrafficControl.AfterLeave += (car, siteId) =>
            {
                LeaveArea(car, siteId);
            };
        }

        [MethodMember(Name = "启动进程", Description = "开始交通监控")]
        public void StartTrafficControl()
        {
            if (InitTrafficConfig()) { status.status = "已启动"; }
        }

        [MethodMember(Name = "停止进程", Description = "停止交通监控")]
        public void StopTrafficControl()
        {
            status.status = "已停止";
        }

        [MethodMember(Name = "查看管制区")]
        public void ShowViewer()
        {
            var viewer = new TrafficInterlockViewer();
            viewer.Show();
        }

        /// <summary>
        /// 初始化交管配置文件
        /// </summary>
        /// <returns></returns>
        private bool InitTrafficConfig()
        {
            try
            {
                string ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "traffic.json");

                if (File.Exists(ConfigPath))
                {
                    TrafficAreaList = JsonConvert.DeserializeObject<List<TrafficArea>>(File.ReadAllText(ConfigPath));

                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine("初始化交管配置文件失败: " + ex.Message); return false;
            }
        }

        /// <summary>
        /// 判断小车是否可以进入区域
        /// </summary>
        /// <param name="car"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        public bool EnterArea(AbstractCar car, int siteId)
        {
            var TrafficAreas = TrafficAreaList.FindAll(area => area.SiteList.Contains(siteId) && area.IsEnable);

            if (TrafficAreas.Count == 0) { return true; }

            if (!TrafficAreas.Exists(t => t.IsOccupy && t.ControllerName != car.id.ToString()))
            {
                lock (TrafficAreaList)
                {
                    TrafficAreas.ForEach(t => { t.IsOccupy = true; t.ControllerName = car.id.ToString(); });
                }

                Console.WriteLine($"小车 {car.id} 进入了交管区域 {string.Join(",", TrafficAreas.Select(t => t.AreaName))}");

                return true;
            }

            return false;
        }

        /// <summary>
        /// 离开区域
        /// </summary>
        /// <param name="car"></param>
        /// <param name="siteId"></param>
        /// <returns></returns>
        public bool LeaveArea(AbstractCar car, int siteId)
        {
            var TrafficAreas = TrafficAreaList.FindAll(area => area.SiteList.Contains(siteId) && area.IsEnable);

            if (TrafficAreas.Count == 0) { return true; }

            foreach (var item in TrafficAreas)
            {
                var Sites = SimpleLib.GetAllSites().Where(s => item.SiteList.Contains(s.id)).ToList();

                if (!Sites.Exists(t => t.status.owner == car.id))
                {
                    lock (TrafficAreaList)
                    {
                        item.ControllerName = string.Empty; item.IsOccupy = false;
                    }

                    Console.WriteLine($"小车 {car.id} 离开了交管区域 {item.AreaName}");
                }
            }

            return true;
        }
    }

    public class TrafficArea
    {
        /// <summary>
        /// 区域稳定标识，用于界面编辑/批量删除时避免行索引错位。
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 区域名称
        /// </summary>
        public string AreaName { get; set; }

        /// <summary>
        /// 区域站点集合
        /// </summary>
        public List<int> SiteList { get; set; }

        /// <summary>
        /// 控制权
        /// </summary>
        [JsonIgnore]
        public string ControllerName { get; set; }

        /// <summary>
        /// 是否被占用
        /// </summary>
        [JsonIgnore]
        public bool IsOccupy { get; set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnable { get; set; }
    }
}
