using Aitex.Core.RT.Event;
using Aitex.Core.RT.IOCore;
using Aitex.Core.RT.SCCore;
using Aitex.Core.RT.Tolerance;
using System.Xml;

namespace Aitex.Core.RT.Device.Devices
{
    public class IoPressureBalanceChecker : BaseDevice, IDevice
    {
        private readonly AIAccessor _aiValue1 = null;
        private readonly AIAccessor _aiValue2 = null;
        private readonly string _formatString = "0.0";

        private double _threshold = 8;
        private bool _isWarning = true;
        private double _value = 0;

        /// <summary>
        /// 误差超限警告检查器
        /// </summary>
        private readonly ToleranceChecker _balanceChecker;

        public string Value => _value.ToString(_formatString);
        public IoPressureBalanceChecker(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
        {
            _aiValue1 = ParseAiNode("aiValue1", node, ioModule);
            _aiValue2 = ParseAiNode("aiValue2", node, ioModule);

            _balanceChecker = new ToleranceChecker(5);

            if (node.HasAttribute("formatString"))
                _formatString = string.IsNullOrEmpty(node.GetAttribute("formatString")) ? "F5" : node.GetAttribute("formatString");
        }

        public bool Initialize()
        {
            _threshold = SC.GetValue<double>($"PM.{Module}.Heater.PressureBalanceDifference");
            return true;
        }

        private bool ResetChecker()
        {
            _balanceChecker.Reset(5);
            return true;
        }

        public void Reset()
        {
            _balanceChecker.Reset(5);
        }

        public void Terminate()
        {
            _balanceChecker.Reset(5);
        }

        protected override void HandleMonitor()
        {
            _value = _aiValue1.Value - _aiValue2.Value;
            _balanceChecker.Monitor(_value, -_threshold, _threshold, 5);
            if (_balanceChecker.Trig)
            {
                var alarmLevel = SC.SafeGetStringValue($"PM.{Module}.Heater.PressureImbalanceAlarmLevel", "Warning");
                if (alarmLevel == "Warning")
                {
                    EV.PostWarningLog(Module, $"PT1:{_aiValue1}({_aiValue1.Value})/PT2:{_aiValue2}({_aiValue2.Value}) Pressure out of balance(threshold:{_threshold})");
                } 
                else
                {
                    EV.PostAlarmLog(Module, $"PT1:{_aiValue1}({_aiValue1.Value})/PT2:{_aiValue2}({_aiValue2.Value}) Pressure out of balance(threshold:{_threshold})");
                }
                    
            }
            
        }
    }
}
