using BPASmartClient.EventBus;
using BPASmartClient.Helper;
using BPASmartClient.JakaRobot;
using BPASmartClient.Model;
using BPASmartClient.Peripheral;
using static BPASmartClient.EventBus.EventBus;

namespace BPASmartClient.JAKA
{
    public class JakaMachine : BasePeripheral
    {
        JaKaHelper jaKaHelper = new JaKaHelper();
        public override void Init()
        {
            jaKaHelper.Connect(communicationPar.IPAddress);

            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                IsConnected = jaKaHelper.IsConnected;
                if (!IsConnected) IsWork = false;
                while (IsConnected)
                {
                    IsWork = true;
                    if (status != null)
                    {
                        SetStatus("GetProgramStatus", (int)jaKaHelper.GetProgramStatus());
                        SetStatus("Get_RobotAO1", jaKaHelper.Get_RobotAO1());
                        SetStatus("Get_RobotDI0", jaKaHelper.Get_RobotDI(0));
                        SetStatus("Get_RobotDI1", jaKaHelper.Get_RobotDI(1));
                        SetStatus("Get_RobotDI2", jaKaHelper.Get_RobotDI(2));
                        SetStatus("Get_RobotDI3", jaKaHelper.Get_RobotDI(3));
                    }
                    Thread.Sleep(500);
                }
                Thread.Sleep(1000);
            }), $"设备[{DeviceId}]节卡机器人读取线程", true);



            EventBus.EventBus.GetInstance().Subscribe<WriteJaka>(DeviceId, delegate (IEvent @event, EventCallBackHandle callBack)
            {
                if (@event == null) return;
                var par = @event as WriteJaka;
                switch (par?.TagName)
                {
                    case "Power_On":
                        jaKaHelper.Power_On();
                        break;
                    case "Enable_robot":
                        jaKaHelper.Enable_robot();
                        break;
                    case "Set_RobotAO1":
                        if (par?.Value is int intvalue) jaKaHelper.Set_RobotAO1(intvalue);
                        break;
                    case "JaKaProgramName":
                        if (par?.Value is string stringvalue) jaKaHelper.JaKaProgramName(stringvalue);
                        break;
                    case "JakaDOutput":
                        if (par?.Value is bool DO_value && par?.DO_Index is int DO_Index) jaKaHelper.Set_RobotDO(DO_Index, DO_value);
                        break;
                    default:
                        break;
                }
            });
        }

        //public override void ReadData(string address)
        //{

        //}

        public override void Start()
        {
        }

        public override void Stop()
        {
        }

        public override void WriteData(string address, object value)
        {

        }

        protected override void InitStatus()
        {
        }
    }
}