using Aitex.Core.RT.OperationCenter;
using System;
using System.Collections.Generic;
using System.Xml;

namespace Aitex.Core.RT.Device.PmDevices
{
    public class RecipeValveAction : BaseDevice, IDevice
    {
        /// <summary>
        /// 当前对象设置气阀的集合
        /// </summary>
        private readonly List<ValveActionData> _valveList = new();

        public RecipeValveAction(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");
            DeviceID = node.GetAttribute("schematicId");

            InitializeIValve(node);
        }

        /// <summary>
        /// 根据XML配置创建气阀控制对象
        /// </summary>
        /// <param name="node"></param>
        private void InitializeIValve(XmlElement node)
        {
            XmlNodeList valveNodes = node.GetElementsByTagName("Valve");
            foreach (XmlElement xmlElement in valveNodes)
            {
                string valveName = xmlElement.GetAttribute("Name");
                ValveActionData valveData = new(Module, Name, valveName);

                foreach (XmlAttribute attributes in xmlElement.Attributes)
                {
                    if (attributes.Name.Contains("Name"))
                        continue;
                    if (String.IsNullOrWhiteSpace(attributes.Value))
                        continue;
                    valveData.AddDictionary(attributes.Name, Convert.ToBoolean(attributes.Value));
                }
                AddValveList(valveData);
            }
        }

        private void AddValveList(ValveActionData valveData)
        {
            if (_valveList.Exists(p => p.Name == valveData.Name))
                System.Diagnostics.Debug.Assert(false, $"{Module} {Name} {valveData.Name} Dictionary contains key:RecipeValveAction");
            else
                _valveList.Add(valveData);
        }

        public bool Initialize()
        {
            OP.Subscribe($"{Module}.{Name}.SetValve", SetValve);

            return true;
        }

        private bool SetValve(out string reason, int time, object[] param)
        {
            return SetValve(out reason, param[0].ToString());
        }

        /// <summary>
        /// 循环遍历气阀需要设定的值
        /// </summary>
        /// <param name="reason"></param>
        /// <param name="flowMode"></param>
        /// <returns></returns>
        private bool SetValve(out string reason, string flowMode)
        {
            reason = "";
            foreach (var valve in _valveList)
            {
                if (!valve.SetValve(flowMode, out reason))
                    return false;
            }
            return true;
        }

        public void Terminate()
        {
        }

        public void Reset()
        {
        }
    }
}