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

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

        public SimulatorAI_AORandom(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("Random");
            foreach (XmlElement xmlElement in valveNodes)
            {
                AI_AORandomData randomData = new AI_AORandomData()
                {
                    Type = xmlElement.GetAttribute("type"),
                    Name = xmlElement.GetAttribute("ioName"),
                    BaseValue = Convert.ToSingle(xmlElement.GetAttribute("baseValue"))
                };
                AI_AOList.Add(randomData);
            }
        }

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

        protected virtual void Random()
        {
            foreach (var ai_ao in AI_AOList)
            {
                if (ai_ao.Type == "AI")
                    IO.AI[$"{Module}.{ai_ao.Name}"].Value = ai_ao.BaseValue + (float)_rnd.NextDouble();
                else if (ai_ao.Type == "AO")
                    IO.AO[$"{Module}.{ai_ao.Name}"].Value = ai_ao.BaseValue + (float)_rnd.NextDouble();
            }
        }

        public bool Initialize()
        {
            return true;
        }

        public void Reset()
        {

        }

        public void Terminate()
        {

        }
    }

    public class AI_AORandomData
    {
        public string Type { get; set; }
        public string Name { get; set; }
        public float BaseValue { get; set; }
    }
}
