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

namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.UPS
{
    public class UPSGetHandler : UPSHandler
    {
        public UPSGetHandler(UPSBase device, string name, string messageType, string Oid)
            : base(device, Oid)
        {
            Name = name;
            MessageType = messageType;
        }

        public override bool HandleMessage(MessageBase msg, out bool handled)
        {
            var result = msg as UPSMessage;
            handled = false;
            if (!result.IsResponse) return true;

            try
            {
                foreach (var dic in result.oidic)
                {
                    var oid = Device.Oids.FirstOrDefault(m => m.Value.Substring(1) == dic.Key);
                    if (oid.Key == null)
                    {
                        continue;
                    }
                    if (oid.Key.Contains("InputVoltage"))
                    {
                        Device.ParseInputVoltage(dic.Value);
                    }
                    else if (oid.Key.Contains("BatteryVoltage"))
                    {
                        Device.ParseBatteryVoltage(dic.Value);
                    }
                    else if (oid.Key.Contains("BatteryRemainsTime"))
                    {
                        Device.ParseBatteryRemainsTime(dic.Value);
                    }
                    else if (oid.Key.Contains("BatteryUnderResidue"))
                    {
                        Device.SetBatteryUnderResidue(Convert.ToInt32(dic.Value));
                    }
                    else if (oid.Key.Contains("upsOutputSource"))
                    {
                        Device.ParseOutputSource(dic.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                LOG.Write(ex.Message);
            }
            Device.IsReceive = true;
            Device._connectTimes = 0;
            handled = true;
            return true;
        }
    }
}
