using System;
using System.Xml;
using Aitex.Core.RT.DataCenter;
using Aitex.Core.RT.Device.Unit;
using Aitex.Core.RT.Event;
using Aitex.Core.RT.IOCore;
using Aitex.Core.RT.SCCore;

namespace Aitex.Core.RT.Device.Devices
{
    public partial class IoPTOffsetAndK : BaseDevice, IDevice, IPressureMeter
    {
        public double PTOffset
        {
            get
            {
                return _aoOffset == null ? 0 : (_isFloatAioType ? _aoOffset.Value : _aoOffset.Value);
            }
            set
            {
                if (_aoOffset != null)
                {
                    if (_isFloatAioType)
                        _aoOffset.Value = (float)value;
                    else
                        _aoOffset.Value = (short)value;
                }
            }
        }


        private AOAccessor _aoOffset = null;
       
        private bool _isFloatAioType = false;

        

        public IoPTOffsetAndK(string module, XmlElement node, string ioModule = "")
        {
            var attrModule = node.GetAttribute("module");
            Module = string.IsNullOrEmpty(attrModule) ? module : attrModule;
            Name = node.GetAttribute("id");
            Display = node.GetAttribute("display");
            _isFloatAioType = !string.IsNullOrEmpty(node.GetAttribute("aioType")) && (node.GetAttribute("aioType") == "float");
            _aoOffset = ParseAoNode("aoOffset", node, ioModule);
        }

        public bool Initialize()
        {
            DATA.Subscribe($"{Module}.AllOffset.{Name}", () => PTOffset);
            SC.RegisterValueChangedCallback($"PM.{Module}.{Display}.{Name}", (o) => { Set_Callback(o); });
            return true;
        }
        public void Set_Callback(object obj = null)
        {
            try
            {
                double scValue = 0;

                if (obj == null)
                    scValue = SC.GetValue<double>($"PM.{Module}.{Display}.{Name}");
                else
                    scValue = (double)obj;
                
                PTOffset = scValue;
                EV.PostInfoLog(Module, $"Set PM.{Module}.{Display}.{Name} = {scValue}OK.");
            }
            catch (Exception ex)
            {
                EV.PostWarningLog(Module, $"Set PM.{Module}.{Display}.{Name} Error:" + ex.Message);
            }
        }
        public void Terminate()
        {

        }
        public void Monitor()
        {

        }
        public void Reset()
        {

        }
    }
}
