using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SimpleLite;
using SimpleCore;
using SimpleCore.Library;
using StandardScene.ChargeStationType;

namespace StandardScene.Charge
{
    /// <summary>
    /// 充电桩udp监听
    /// </summary>
    public class ChargeUdpService
    {
        public Thread ListenerThread;

        public ChargeUdpService()
        {
            ListenerThread = new Thread(ListenerProcess);
            ListenerThread.Start();
        }

        private static async void ListenerProcess()
        {
            var messageService = CommunicationMessageService.Instance;
            using (UdpClient udpListener = new UdpClient(40001))
            {
                Diagnosis.Log($"Listening for UDP messages on port {40001}");
                while (true)
                {
                    try
                    {
                        var result = await udpListener.ReceiveAsync();
                        var remoteEndPoint = result.RemoteEndPoint;
                        var message = result.Buffer;
                        messageService.AddReceiveMessage(remoteEndPoint.Address.ToString(), 40001, BitConverter.ToString(message).Replace("-", " "), "FRLDShort");
                        Diagnosis.Log($"ChargeStation ADD:[{BitConverter.ToString(message).Replace("-", " ")}]","UDP返回报文信息",true);
                        var chargeMission = SimpleProject.proj.Missions.OfType<StandardChargeMission>().FirstOrDefault();
                        if (chargeMission == null) continue;
                        var chargeStation =
                            chargeMission.ChargeStations.FirstOrDefault(c =>
                                c.Value.Ip == remoteEndPoint.Address.ToString()).Value;
                        if (chargeStation == null) continue;
                        if (message.Length > 28)
                            chargeStation.IsSafe = message[28] == 1;
                        chargeStation.OnUdpMessage(message);
                    }
                    catch (Exception e)
                    {
                        // 单帧异常（含越界/半包）不得中断 UDP 监听线程
                        Diagnosis.Log($"充电UDP接收处理异常: {e.Message}", "UDP", true);
                    }
                }
            }
        }
    }
}
