using MegaRobo.Connections;
using MegaRobo.Connections.Sockets.Tcp;
using MegaRobo.Contract;
using MegaRobo.ControlDevices.Abstractions;
using MegaRobo.Logger;
using Npgsql.Replication.PgOutput.Messages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MegaRobo.C00225155.ControlDevices
{
    public class LowTemperatureMagneticStirService : ConnectorBase<MegaTcpClient>
    {
        public override async Task<string> Initialize(ICoreService coreService, params object[] args)
        {
            this.CoreService = coreService;
            try
            {
                base.CoreService = coreService;
                if (args is [IPEndPoint remoteHost, ..])
                {
                    base.ConnectorAdapter = new MegaTcpClient
                    {
                        Logger = coreService.Logger,
                        Name = base.Name
                    };
                    if (base.ConnectorAdapter != null)
                    {
                        base.ConnectorAdapter.DataReceived += ConnectorOnDataReceived;
                    }

                    ConnectionState = await base.ConnectorAdapter.ConnectAsync(remoteHost);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                return await Task.FromResult(ex.Message);
            }
            return string.Empty;
        }

        private void ConnectorOnDataReceived(object sender, TcpMessage tcpMsg)
        {
            if (tcpMsg is null)
                return;
            var msg = tcpMsg.ParseStirng();
            if (string.IsNullOrEmpty(msg)) return;
        }

        public override Task<ConnectionState> ReconnectAsync()
        {
            return base.ReconnectAsync();
        }

        /// <summary>
        /// 检测连接状态
        /// </summary>
        /// <returns></returns>
        public override async Task<ConnectionState> CheckConnected()
        {
            var state = ConnectionState.None;
            if (ConnectorAdapter is not null)
            {
                state = await ConnectorAdapter.CheckConnectedAsync();
            }
            ConnectionState = state;
            return state;
        }

        /// <summary>
        /// 设置电机转速
        /// </summary>
        /// <param name="motorSpeed"></param>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task<bool> SetMotorSpeed(int motorSpeed, byte deviceId)
        {
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendMotorControl(motorSpeed, deviceId), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return false;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            return result.IsSuccess;
        }

        /// <summary>
        /// 设置温度
        /// </summary>
        /// <param name="temperature"></param>
        /// <param name="deviceId"></param>
        ///  <param name="offTemp">关闭温度</param>
        /// <returns></returns>
        public async Task<bool> SetTemperature(int temperature, byte deviceId, bool offTemp)
        {
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendSetTemp(temperature, deviceId, offTemp), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return false;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            return result.IsSuccess;
        }

        /// <summary>
        /// 设置加热温度，除霜
        /// </summary>
        /// <param name="hottemperature"></param>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task<bool> SetHotTemperature(int hottemperature, byte deviceId)
        {
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendSetHotTemp(hottemperature, deviceId), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return false;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            return result.IsSuccess;
        }

        /// <summary>
        /// 获取电机转速
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task<int> GetActualMotorSpeed(byte deviceId)
        {
            int motorSpeed = 0;
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendReadMotorSpeedRequest(deviceId), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return 0;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            if (result.IsSuccess)
            {
                motorSpeed = (int)result.Data["实际转速"];
            }
            return motorSpeed;
        }

        /// <summary>
        /// 获取当前温度
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task<int> GetActualTemperature(byte deviceId)
        {
            int temperature = 0;
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendReadTempRequest(deviceId), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return 0;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            if (result.IsSuccess)
            {
                temperature = (int)result.Data["实际温度（℃）"];
            }
            return temperature;
        }

        /// <summary>
        /// 获取开关盖状态
        /// </summary>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        public async Task<string> GetLidStatus(byte deviceId)
        {
            string status = string.Empty;
            var tcpMessage = await ConnectorAdapter.WriteAndGetReplyAsync(LowTemperatureUartHCM.SendReadIoStatusRequest(deviceId), TimeSpan.FromSeconds(3));
            if (tcpMessage is null)
                return string.Empty;
            ParseResult result = LowTemperatureUartHCM.ParseReceivedFrame(tcpMessage.Data);
            if (result.IsSuccess)
            {
                status = result.Data["开关盖状态"].ToString() ?? string.Empty;
            }
            return status;
        }
    }
}
