using Aitex.Core.RT.Device;
using Aitex.Core.RT.IOCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;

namespace MECF.Framework.Simulator.Core
{
    public class SimulatorIoValve : BaseDevice, IDevice
    {
        protected Dictionary<string, string> DI_DOList = new Dictionary<string, string>();

        public SimulatorIoValve(string module, XmlElement node, string ioModule) : base(module, node, ioModule)
        {
            InitializeIValve(node);
        }

        /// <summary>
        /// 根据XML配置创建气阀控制对象
        /// </summary>
        /// <param name="node"></param>
        protected virtual void InitializeIValve(XmlElement node)
        {
            string valveName = "";
            try
            {
                XmlNodeList valveNodes = node.GetElementsByTagName("IoValve");
                foreach (XmlElement xmlElement in valveNodes)
                {
                    string diName = xmlElement.GetAttribute("diOpen");
                    string doName = xmlElement.GetAttribute("doOpen");
                    valveName= diName;
                    if (!DI_DOList.ContainsKey(diName) && !DI_DOList.ContainsKey(doName))
                        DI_DOList.Add(diName, doName);

                    var isDefaultOpen = xmlElement.GetAttribute("isDefaultOpen");
                    if (!String.IsNullOrWhiteSpace(isDefaultOpen))
                        IO.DO[$"{Module}.{doName}"].Value = Convert.ToBoolean(isDefaultOpen);
                }
            }
            catch (Exception ex)
            {
                Debug.Assert(false, $"{DI_DOList.LastOrDefault().Value}--检查气动阀仿真配置");
                throw;
            }
            
        }

        protected override void HandleMonitor()
        {
            DoValueToDI();
        }

        protected void DoValueToDI()
        {
            foreach (var di_do in DI_DOList)
            {
                IO.DI[$"{Module}.{di_do.Key}"].Value = IO.DO[$"{Module}.{di_do.Value}"].Value;
            }
        }

        public bool Initialize()
        {
            return true;
        }

        public void Reset()
        {

        }

        public void Terminate()
        {

        }
    }
}
