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

namespace MECF.Framework.Simulator.Core
{
    public class SimulatorMFC : BaseDevice, IDevice
    {
        protected Dictionary<string, string> AI_AOList = new Dictionary<string, string>();
        private readonly Random _rnd = new Random();

        public SimulatorMFC(string module, XmlElement node, string ioModule = "") : base(module, node, ioModule)
        {
            InitializeIValve(node);
        }

        /// <summary>
        /// 根据XML配置创建MFC控制对象
        /// </summary>
        /// <param name="node"></param>
        protected virtual void InitializeIValve(XmlElement node)
        {
            XmlNodeList valveNodes = node.GetElementsByTagName("IoMfc");
            foreach (XmlElement xmlElement in valveNodes)
            {
                string aiFlow = xmlElement.GetAttribute("aiFlow");
                string aoFlow = xmlElement.GetAttribute("aoFlow");
                if (!AI_AOList.ContainsKey(aiFlow) && !AI_AOList.ContainsKey(aoFlow))
                    AI_AOList.Add(aiFlow, aoFlow);

            }
        }

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

        protected virtual void Ramp()
        {
            foreach (var ai_ao in AI_AOList)
            {
                float setpoint = 0;
                float result = 0;
                float current = 0;
                if (IO.AI[$"{Module}.{ai_ao.Key}"] != null)
                {
                    current = IO.AI[$"{Module}.{ai_ao.Key}"].Value;
                    setpoint = IO.AO[$"{Module}.{ai_ao.Value}"].Value;
                }


                if (current >= setpoint)
                {
                    result = current - 50;
                    if (result < setpoint)
                        result = setpoint;
                }
                if (current < setpoint)
                {
                    result = current + 50;
                    if (result > setpoint)
                        result = setpoint;
                }

                result = result + (float)_rnd.NextDouble();

                IO.AI[$"{Module}.{ai_ao.Key}"].Value = result;
            }
        }

        public bool Initialize()
        {
            return true;
        }

        public void Reset()
        {

        }

        public void Terminate()
        {

        }
    }
}
