using Aitex.Core.RT.Log;
using MECF.Framework.Common.Communications;
using System;
using System.Linq;

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
    public class HikMessage: MessageBase
    {
        public string RawMessage { get; set; } = "";

        public double[] paras;
        public bool Result { get; set; } = false;
    }
    public class HikMVConnection : TCPPortConnectionBase
    {
        public HikMVConnection(string address, string newline = "\r", bool isAsciiMode = true) : base(address, newline, isAsciiMode)
        {

        }

        public override bool SendMessage(string message)
        {
            return base.SendMessage(message);
        }

        protected override MessageBase ParseResponse(string rawText)
        {
            HikMessage msg = new HikMessage();
            msg.RawMessage = rawText;

            if (msg.RawMessage.Length == 0)
            {
                LOG.Error($"empty response");
                msg.IsFormatError = true;
                return msg;
            }
            else if (msg.RawMessage.StartsWith("OK")&& msg.RawMessage.Contains(':'))
            {
                try
                {
                    var m = msg.RawMessage.Split(':');
                    var values = m[1].Split(',');
                    msg.paras = new double[values.Length];
                    for (int i = 0; i < values.Length; i++)
                    {
                        msg.paras[i]= Convert.ToDouble(values[i]);
                    }
                    msg.Result = true;
                }
                catch (Exception)
                {
                    LOG.Error($"Convert Response Failed From Camera{Address}({msg.RawMessage})");
                    msg.RawMessage = $"Convert Response Failed From Camera{Address}({msg.RawMessage})";
                }
                
            }
            else if (msg.RawMessage.StartsWith("NG"))
            {
                LOG.Error($"NG Response From Camera{Address}");
            }
            else
            {
                LOG.Error($"Unknown Response From Camera{Address}({msg.RawMessage})");
                msg.RawMessage = $"Unknown Response From Camera{Address}({msg.RawMessage})";
            }

            msg.IsResponse = true;
            msg.IsAck = true;

            return msg;
        }
    }
}
