using Aitex.Core.RT.Log;
using Aitex.Core.RT.Routine;
using PunkHPX8_Core;
using MECF.Framework.Common.Beckhoff.AxisProvider;
using MECF.Framework.Common.CommonData.PUF;
using MECF.Framework.Common.Routine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PunkHPX8_RT.Devices.AXIS.Galil
{
    public class GalilStopPositionRoutine : RoutineBase, IRoutine
    {
        private enum StopPositionStep
        {
            SetStop,
            WriteTargePosition,
            End
        }
        #region 常量
        private const string TARGET_POSITION = "TargetPosition";
        private const int STOP_CODE = 4;
        #endregion
        #region 内部变量
        private JetAxisBase _axis;
        private int _targetPosition;
        private GalilCommonAxis _galilCommonAxis;
        /// 
        /// SRD rotation Provider对象
        /// 
        private BeckhoffProviderAxis _rotationProviderAxis;
        #endregion
        public GalilStopPositionRoutine(string module, JetAxisBase axis,GalilCommonAxis galilCommonAxis) : base(module)
        {
            _axis = axis;
            _galilCommonAxis = galilCommonAxis;
        }
        public void Abort()
        {
            Runner.Stop("Manual Abort");
        }
        public RState Monitor()
        {
            Runner.Run(StopPositionStep.SetStop, SetStop, CheckStop, _delay_2s)
                .Run(StopPositionStep.WriteTargePosition, () => { return WriteTargetPosition(); }, NullFun, 100)
                .End(StopPositionStep.End, NullFun, 100);
            return Runner.Status;
        }
        /// 
        /// 设置停止
        /// 
        /// 
        private bool SetStop()
        {
            return _galilCommonAxis.WriteStop();
        }
        /// 
        /// 检验是否停止
        /// 
        /// 
        private bool CheckStop()
        {
            return _axis.MotionData.StopCode ==STOP_CODE&&!_axis.IsRun;
        }
        /// 
        /// 设置目标位置为当前位置
        /// 
        /// 
        private bool WriteTargetPosition()
        {
            double scale = _rotationProviderAxis.ScaleFactor;
            _targetPosition = (int)Math.Ceiling(_axis.MotionData.MotorPosition * scale);
            return _galilCommonAxis.WriteAbsolutePosition(_targetPosition);
        }
        public RState Start(params object[] objs)
        {
            _rotationProviderAxis = BeckhoffAxisProviderManager.Instance.GetAxisProvider($"{Module}");
            if (_rotationProviderAxis == null)
            {
                LOG.WriteLog(eEvent.ERR_AXIS, Module, $"{Module} Axist Provider is not exist");
                return RState.Failed;
            }
            return Runner.Start(Module, "Stop Position");
        }
    }
}