using Aitex.Core.RT.Device;
using Aitex.Core.RT.Log;
using Aitex.Core.RT.Routine;
using Aitex.Core.RT.SCCore;
using CyberX8_Core;
using MECF.Framework.Common.Beckhoff.ModuleIO;
using MECF.Framework.Common.IOCore;
using MECF.Framework.Common.Routine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CyberX8_RT.Devices.SRD
{
    public class SrdCommonLiftUpRoutine : RoutineBase, IRoutine
    {
        #region 常量 
        private const string LIFT_UP = "LiftUp";
        #endregion
        private enum LiftUpStep
        {
            LiftUp,
            Delay,
            End
        }
        #region 内部变量
        private bool _liftUp;
        private SrdCommonDevice _srdCommon;
        private int _timeout = 1000;
        #endregion
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="module"></param>
        public SrdCommonLiftUpRoutine(string module) : base(module)
        {
        }

        public void Abort()
        {
            Runner.Stop("Manual Abort");
        }

        public RState Monitor()
        {
            Runner.Run(LiftUpStep.LiftUp, LiftUp, CheckLiftUpStatus, _timeout)
                .DelayIf(LiftUpStep.Delay, !_liftUp, 500)
                .End(LiftUpStep.End, NullFun, 100);
            return Runner.Status;
        }

        private bool LiftUp()
        {
            string ioName = BeckhoffModuleIOManager.Instance.GetIoNameByInnerModuleName($"{Module}.{LIFT_UP}");
            return IOModuleManager.Instance.WriteIoValue(ioName, _liftUp);
        }

        private bool CheckLiftUpStatus()
        {
            if (_srdCommon.CommonData.LiftUpStatus == _liftUp)
            {
                LOG.WriteLog(eEvent.INFO_SRD, Module, $"LiftUp Sensor is {_liftUp}");
                return true;
            }
            else
            {
                LOG.WriteLog(eEvent.INFO_SRD, Module, $"LiftUp Sensor is {_liftUp}");
                return false;
            }
        }

        public RState Start(params object[] objs)
        {
            _liftUp = (bool)objs[0];
            _srdCommon = DEVICE.GetDevice<SrdCommonDevice>($"{Module}.Common");
            if (_liftUp)
            {
                return Runner.Start(Module, "Lift Up On");
            }
            else
            {
                return Runner.Start(Module, "Lift Up Off");
            }
        }
    }
}