using BPA.SingleDevice.Interface;

namespace BPA.SingleDevice.Business
{
    /// <summary>配料机，在这个程序中，指的是味魔方。</summary>
    public class Batcher : IBatchcer
    {
        public int ID { get; set; }
        public bool BatchComplete { get; set; }
        public bool AllowBatching { get; set; }
        public bool IsConnected { get => modbus.IsConnected(); }

        private string iP = "192.168.6.100";
        private int port = 502;
        private ModbusTcp modbus = new();

        public async Task InitialAsync()
        {
            await Task.Run(() =>
            {
                modbus.WithModbusTcp(iP, port).UseConnected(() =>
                {
                    TaskManage.GetInstance.StartLong(() =>
                    {
                        BatchComplete = modbus.Read<bool>("LB1000".ToModbusAdd()).Content;
                    }, $"Batcher【{ID}】:ReadData", true);
                });
            });
        }

        public bool StartBatching()
        {
            try
            {
                var result = modbus.Write<bool>("LB1001".ToModbusAdd(), true);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.Show(ex.Message);
                return false;
            }
        }

        public bool ResetCompleted()
        {
            try
            {
                var result = modbus.Write<bool>("LB1000".ToModbusAdd(), false);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.Show(ex.Message);
                return false;
            }
        }

        public bool WriteBatchData(ushort[] value)
        {
            ushort[] newValue = new ushort[value.Length];
            for (int i = 0; i < value.Length; i++)
            {
                newValue[i] = (ushort)(value[i] * 10);
            }
            try
            {
                var result = modbus.Write<ushort[]>("LW1000".ToModbusAdd(), newValue);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {
                MessageLog.GetInstance.Show(ex.Message);
                return false;
            }
        }

        public void SetCommParam(int id, string ip, int port = 502)
        {
            this.iP = ip;
            this.port = port;
            this.ID = id;
        }
    }
}