using Aitex.Core.RT.Device;
using Aitex.Core.RT.Routine;
using MECF.Framework.Common.Beckhoff.ModuleIO;
using MECF.Framework.Common.Routine;
using MECF.Framework.Common.TwinCat;
using CyberX8_Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MECF.Framework.Common.IOCore;
namespace CyberX8_RT.Devices.SRD
{
    public class SrdCommonDoorCloseRoutine : RoutineBase, IRoutine
    {
        #region 常量 
        private const string DOOR_CLOSE = "DoorClose";
        #endregion
        private enum CloseStep
        {
            DoorClose,
            End
        }
        #region 内部变量
        private bool _closeValue;
        private SrdCommonDevice _srdCommon;
        private int _timeout = 2000;
        #endregion
        /// 
        /// 构造函数
        /// 
        /// 
        public SrdCommonDoorCloseRoutine(string module) : base(module)
        {
        }
        public void Abort()
        {
            Runner.Stop("Manual Abort");
        }
        public RState Monitor()
        {
            Runner.Run(CloseStep.DoorClose, DoorClose, CheckDoorStatus, _timeout)
                .End(CloseStep.End, NullFun, 100);
            return Runner.Status;
        }
        private bool DoorClose()
        {
            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{DOOR_CLOSE}");
            return IOModuleManager.Instance.WriteIoValue(ioName, _closeValue);
        }
        private bool CheckDoorStatus()
        {
            return _srdCommon.CommonData.DoorClosed == _closeValue && _srdCommon.CommonData.DoorOpened == !_closeValue;
        }
        public RState Start(params object[] objs)
        {
            _closeValue = (bool)objs[0];
            _srdCommon = DEVICE.GetDevice($"{Module}.Common");
            if (_closeValue)
            {
                return Runner.Start(Module, "Door Close");
            }
            else
            {
                return Runner.Start(Module, "Door Open");
            }
        }
    }
}