using BPA.Communication;
using BPA.SingleDevice.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPA.Helper;
using BPA.Model;
using BPA.SingleDevice.Helper;
using System.Threading;

namespace BPA.SingleDevice.Business
{
    public abstract class DeviceAbs : IDeviceAbs
    {
        string IpAddress { get; set; }
        EDeviceType DeviceType { get; set; }
        int Port { get; set; }
        public Action<EDeviceType> Complete { get; set; }
        ModbusTcp mt { get; set; } = new ModbusTcp();
        public Action<int> ArrivalFingerPos { get; set; }
        public bool AllowBatching { get; set; }
        public bool[] DeviceStationDetection { get; set; } = new bool[4];

        public void SetPar(string ip, EDeviceType deviceType, int port = 502)
        {
            IpAddress = ip;
            DeviceType = deviceType;
            Port = port;
        }

        public void Start()
        {
            mt.WithModbusTcp(IpAddress, Port).UseConnected(() =>
            {
                TaskManage.GetInstance.StartLong(new Action(() =>
                {
                    if (DeviceType != EDeviceType.Conveyor)
                    {
                        mt.Read<bool>("LB12").OnSuccess(s =>
                        {
                            if (RTrig.GetInstance(DeviceType.ToString()).Start(s))
                            {
                                Complete?.Invoke(DeviceType);
                            }
                        });
                    }
                    else
                    {
                        mt.Read<bool[]>("1", (ushort)DeviceStationDetection.Length).OnSuccess(s =>
                        {
                            for (int i = 0; i < s.Length; i++)
                            {
                                DeviceStationDetection[i] = s[i];
                                if (RTrig.GetInstance($"输送带到位{i + 1}").Start(s[i]))
                                {
                                    ArrivalFingerPos?.Invoke(i + 1);
                                }
                            }
                        });

                        AllowBatching = mt.Read<bool>("5").Content;
                    }
                    Thread.Sleep(1);
                }), DeviceType.ToString(), true);
            });
        }

        public void Stop()
        {
            TaskManage.GetInstance.StopTask(DeviceType.ToString());
        }

        public void WriteControl(ushort[] value)
        {
            mt.Write("LW30".ToModbusAdd(), value);
            mt.Write("LB10".ToModbusAdd(), true);
        }

        public void ConveyorControl(bool value)
        {
            mt.Write("0", value);
        }
    }
}
