using MECF.Framework.Common.Communications;
using System;
using System.Text.RegularExpressions;

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.MachineVision.HikVision
{
    public class HikMVHandler : HandlerBase
    {
        public HikMV Device { get; }
        public string _command;

        public HikMVHandler(HikMV device, string command): base(command)
        {
            Device = device;
            _command = command;
            Name = command;
        }

        public override bool HandleMessage(MessageBase msg, out bool handled)
        {
            HikMessage response = msg as HikMessage;
            ResponseMessage = msg;
            //ParseResult(response.RawMessage);

            if (response.IsAck)
            {
                SetState(EnumHandlerState.Acked);

                if (msg.IsError)
                {
                    //Device.NoteError($"Command '{_command}' Error: {response.Data}:{ErrorString(response.ErrorText)}");
                }
                else
                {
                    SetState(EnumHandlerState.Completed);
                    handled = true;
                    Device.Data = response.paras;
                    Device.RawMessage = response.RawMessage;
                    Device.IsResponded = response.Result;
                    Device.IsProcessing = false;
                    return true;
                }
            }

            handled = false;
            return false;
        }

        private void ParseResult(string rawMessage)
        {
            rawMessage = rawMessage.Replace("\r", "").Replace("\n", "");

            // NG
            // OK_1:xxxx,yyyy\r\n
            var pattern = @"^OK_(\d+):(-?\d+\.\d+|\d+),(-?\d+\.\d+|\d+)$";
            var pattern2 = @"^OK_(\d+):(-?\d+\.\d+|\d+)$";
            if (rawMessage.StartsWith("OK"))
            {
                var m = Regex.Match(rawMessage, pattern);
                if (m.Success)
                {
                    var posX = Convert.ToDouble(m.Groups[2].Value);
                    var posY = Convert.ToDouble(m.Groups[3].Value);
                    Device.Data = [posX, posY];
                    Device.RawMessage = rawMessage;
                }
                else
                {
                    var m2 = Regex.Match(rawMessage, pattern);
                    if (m2.Success)
                    {
                        var posR = Convert.ToDouble(m.Groups[2].Value);
                        Device.Data = [posR];
                        Device.RawMessage = rawMessage;
                    }
                }

            }
        }
    }
}
