using FLY.Thick.Base.Common;
using FlyADBase;
using System.ComponentModel;

namespace FLY.Thick.Base.Server
{
    public class GM_Pause : GM_Base
    {
        public int Delay
        {
            get;
            set;
        }
        public bool Enable
        {
            get;
            set;
        }

        enum STATE
        {
            WAIT_ORG,
            WAIT_RESCAN
        }
        STATE mState;
        DynArea mDynArea;
        GM_AutoScan mGMAutoScan;

        public GM_Pause()
        {
            GMState = CTRL_STATE.PAUSE;
            Enable = false;

        }

        public void Init(FlyAD7 flyad, DynArea dynarea, GM_AutoScan gmAutoScan)
        {
            base.Init(flyad);
            mDynArea = dynarea;
            mGMAutoScan = gmAutoScan;
            mDynArea.PropertyChanged += new PropertyChangedEventHandler(mDynArea_PropertyChanged);

            this.PropertyChanged += new PropertyChangedEventHandler(GM_Pause_PropertyChanged);
        }

        void GM_Pause_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(Enable))
            {
                if (Enable)
                {
                    update_datavalid();
                }
                else
                {
                    if (IsRunning)
                        Stop();
                }
            }
        }
        void update_datavalid()
        {
            if (mDynArea.DataValid)
            {
                switch (mDynArea.ControllerState)
                {
                    case CTRL_STATE.FIX:
                    case CTRL_STATE.PAUSE:
                        mGMAutoScan.Start(Delay);
                        break;
                }
            }
            else
            {
                switch (mDynArea.ControllerState)
                {
                    case CTRL_STATE.SCAN:
                    case CTRL_STATE.AUTOSCAN:
                        Start();
                        break;
                    default:
                        mGMAutoScan.Stop();
                        break;
                }
            }
        }
        void mDynArea_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(mDynArea.DataValid))
            {
                if (Enable)
                    update_datavalid();
            }
        }
        protected override void OnPoll()
        {
            switch (mState)
            {
                case STATE.WAIT_ORG:
                    if (mFlyAD.IsFinish)
                    {
                        mState = STATE.WAIT_RESCAN;
                    }
                    break;
                case STATE.WAIT_RESCAN:
                    break;
            }
        }
        public override void Start()
        {
            base.Start();
            if (!IsRunning) return;
            mState = STATE.WAIT_ORG;
            mFlyAD.Origin();
        }

    }
}
