using Aitex.Core.RT.Device;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.Routine;
using Aitex.Core.RT.SCCore;
using CyberX8_Core;
using CyberX8_RT.Devices.Metal;
using CyberX8_RT.Devices.Reservoir;
using MECF.Framework.Common.Persistent.Reservoirs;
using MECF.Framework.Common.RecipeCenter;
using MECF.Framework.Common.Routine;
using MECF.Framework.Common.ToolLayout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CyberX8_RT.Modules.Metal
{
    public class CompactEmbranceInitializeRoutine : RoutineBase, IRoutine
    {
        private enum InitializeStep
        {
            CheckPowerSupplierConnected,
            LinmotReset,
            LinmotResetWait,
            WHUnclampOn,
            FlowValveOn,
            Delay,
            ManualFlowCheck,
            AutoFlowCheck,
            End
        }
        #region 内部变量
        /// 
        /// 持久化对象
        /// 
        private MetalPersistentValue _persistentValue;
        /// 
        /// 设备对象
        /// 
        private CompactMembranMetalDevice _metalDevice;
        /// 
        /// Reservoir Recipe
        /// 
        private ResRecipe _resRecipe;
        /// 
        /// Cell Flow Delay Time
        /// 
        private int _cellFlowFaultHoldOffTime = 5000;
        /// 
        /// Cell Flow Start Low Limit
        /// 
        private double _cellFlowStartLowLimit = 3.0;
        #endregion
        /// 
        /// 构造函数
        /// 
        /// 
        public CompactEmbranceInitializeRoutine(string module) : base(module)
        {
        }
        /// 
        /// 中止
        /// 
        public void Abort()
        {
            Runner.Stop("Manual Abort");
        }
        /// 
        /// 监控
        /// 
        /// 
        public RState Monitor()
        {
            Runner.Run(InitializeStep.CheckPowerSupplierConnected, CheckPowerSupplierStatus, _delay_1ms)
                .Run(InitializeStep.LinmotReset, _metalDevice.ResetLinmot, _delay_1ms)
                .WaitWithStopCondition(InitializeStep.LinmotResetWait, _metalDevice.CheckLinmotRoutineEnd, _metalDevice.CheckLinmotRoutineError)
                .Run(InitializeStep.WHUnclampOn, WaferHolderUnclampOn, _delay_1ms)
                .Run(InitializeStep.FlowValveOn, () => _metalDevice.CellFlowValveOn("", null), _delay_1ms)
                .Delay(InitializeStep.Delay, _cellFlowFaultHoldOffTime)
                .RunIf(InitializeStep.ManualFlowCheck, _metalDevice.IsManual, ManualFlowCheck, _delay_1ms)
                .RunIf(InitializeStep.AutoFlowCheck, _metalDevice.IsAuto, AutoFlowCheck, _delay_1ms)
                .End(InitializeStep.End, NullFun, _delay_1ms);
            return Runner.Status;
        }
        /// 
        /// 检验Metal A/B 面PowerSupplier通讯状况
        /// 
        /// 
        private bool CheckPowerSupplierStatus()
        {
            if (!_metalDevice.SideAPowerSupplier.IsConnected)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, "side A power is not connected");
                return false;
            }
            if (!_metalDevice.SideBPowerSupplier.IsConnected)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, "side B power is not connected");
                return false;
            }
            return true;
        }
        /// 
        /// WaferHolder Unclamp on
        /// 
        /// 
        private bool WaferHolderUnclampOn()
        {
            return _metalDevice.WaferHolderUnclampOn("", null);
        }
        /// 
        /// 手动检验Flow
        /// 
        /// 
        private bool ManualFlowCheck()
        {
            if (_metalDevice.MetalDeviceData.CellFlow < _cellFlowStartLowLimit)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, $"Flow {_metalDevice.MetalDeviceData.CellFlow} is less than {_cellFlowStartLowLimit}");
                _metalDevice.CellFlowValveOff("", null);
                return false;
            }
            return true;
        }
        /// 
        /// 自动检验Flow
        /// 
        /// 
        private bool AutoFlowCheck()
        {
            if (_metalDevice.MetalDeviceData.CellFlow < _resRecipe.CAFlowRateErrorLow)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, $"Flow {_metalDevice.MetalDeviceData.CellFlow} is less than {_resRecipe.CAFlowRateErrorLow}");
                return false;
            }
            return true;
        }
        /// 
        /// 启动
        /// 
        /// 
        /// 
        public RState Start(params object[] objs)
        {
            _persistentValue = (MetalPersistentValue)objs[0];
            _metalDevice = DEVICE.GetDevice(Module);
            _cellFlowFaultHoldOffTime = SC.GetValue("Metal.CellFlowFaultHoldOffTime");
            _cellFlowStartLowLimit = SC.GetValue("Metal.CellFlowStartLowLimit");
            string reservoir = ReservoirItemManager.Instance.GetReservoirByMetal(Module.ToString());
            CompactMembranReservoirDevice reservoirDevice = DEVICE.GetDevice(reservoir);
            if (reservoirDevice == null)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, $"{reservoir} device is null");
                return RState.Failed;
            }
            if (reservoirDevice.Recipe == null)
            {
                LOG.WriteLog(eEvent.ERR_METAL, Module, $"{reservoir} current recipe is null");
                return RState.Failed;
            }
            _resRecipe = reservoirDevice.Recipe;
            return Runner.Start(Module, "Start C&M Initialize");
        }
    }
}