using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AGVNavigationCore.Models;
using AR;
using arDev;
using COMM;
using static arDev.Narumi;

namespace Project.ViewForm
{
    public partial class fManual : Form
    {
        public fManual()
        {
            InitializeComponent();
            this.FormClosed += FIO_FormClosed;
        }

        private void fManual_Load(object sender, EventArgs e)
        {
            if (PUB.AGV.data.Direction == 'F') radforward.Checked = true;
            else radbackward.Checked = false;

            //if (PUB.AGV.data.Sts == 'L') radleft.Checked = true;
            //else if (PUB.AGV.data.Sts == 'R') radright.Checked = true;
            //else 
            radstrai.Checked = true;

            if (PUB.AGV.data.Speed == 'H') radspdh.Checked = true;
            else if (PUB.AGV.data.Speed == 'M') radspdm.Checked = true;
            else radspdl.Checked = true;

            this.timer1.Start();
        }
        private void FIO_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer1.Stop();
        }

        #region "Z축 커버"

        private void arLabel10_Click(object sender, EventArgs e)
        {

        }



        private void arLabel8_Click(object sender, EventArgs e)
        {


        }

        private void arLabel7_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region "AGV 수동 이동"
        private void arLabel1_Click(object sender, EventArgs e)
        {
            //후진
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA])
            {
                UTIL.MsgE("자동 충전 중입니다\n충전을 해제 하세요");
                return;
            }
            else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM])
            {
                UTIL.MsgE("수동 충전 중입니다\b충전을 해제 하세요");
                return;
            }
            if (PUB.CheckManualChargeMode() == false) return;
            arDev.Narumi.Speed spd = arDev.Narumi.Speed.Low;

            if (radspdh.Checked) spd = arDev.Narumi.Speed.High;
            else if (radspdm.Checked) spd = arDev.Narumi.Speed.Mid;
            arDev.Narumi.Sensor ss = arDev.Narumi.Sensor.PBSOff;
            if (radpbs0.Checked) ss = arDev.Narumi.Sensor.PBSOn;
            PUB.AGV.AGVMoveManual(arDev.Narumi.ManulOpt.BS, spd, ss);
            PUB.sm.SetNewStep(StateMachine.eSMStep.IDLE);

            // [Manual Safety] Clear previous auto-task state
            PUB._virtualAGV.TargetNode = null;
            PUB._virtualAGV.StopPath();
            PUB.NextWorkCmd = ENIGProtocol.AGVCommandHE.Stop; // Clear ACS Command
            PUB.sm.ClearRunStep(); // Clear RunStep sequence
        }

        private void arLabel2_Click(object sender, EventArgs e)
        {
            //전진
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA])
            {
                UTIL.MsgE("자동 충전 중입니다\n충전을 해제 하세요");
                return;
            }
            else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM])
            {
                UTIL.MsgE("수동 충전 중입니다\b충전을 해제 하세요");
                return;
            }
            if (PUB.CheckManualChargeMode() == false) return;
            arDev.Narumi.Speed spd = arDev.Narumi.Speed.Low;
            if (radspdh.Checked) spd = arDev.Narumi.Speed.High;
            else if (radspdm.Checked) spd = arDev.Narumi.Speed.Mid;
            arDev.Narumi.Sensor ss = arDev.Narumi.Sensor.PBSOff;
            if (radpbs0.Checked) ss = arDev.Narumi.Sensor.PBSOn;
            PUB.AGV.AGVMoveManual(arDev.Narumi.ManulOpt.FS, spd, ss);
            PUB.sm.SetNewStep(StateMachine.eSMStep.IDLE);

            // [Manual Safety] Clear previous auto-task state
            PUB._virtualAGV.TargetNode = null;
            PUB._virtualAGV.StopPath();
            PUB.NextWorkCmd = ENIGProtocol.AGVCommandHE.Stop;
            PUB.sm.ClearRunStep();
        }

        private void arLabel3_Click(object sender, EventArgs e)
        {
            //우회전
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA])
            {
                UTIL.MsgE("자동 충전 중입니다\n충전을 해제 하세요");
                return;
            }
            else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM])
            {
                UTIL.MsgE("수동 충전 중입니다\b충전을 해제 하세요");
                return;
            }
            if (PUB.CheckManualChargeMode() == false) return;
            arDev.Narumi.Speed spd = arDev.Narumi.Speed.Low;
            if (radspdh.Checked) spd = arDev.Narumi.Speed.High;
            else if (radspdl.Checked) spd = arDev.Narumi.Speed.Mid;
            arDev.Narumi.Sensor ss = arDev.Narumi.Sensor.PBSOff;
            if (radpbs0.Checked) ss = arDev.Narumi.Sensor.PBSOn;
            PUB.AGV.AGVMoveManual(arDev.Narumi.ManulOpt.RT, spd, ss);
            PUB.sm.SetNewStep(StateMachine.eSMStep.IDLE);

            // [Manual Safety] Clear previous auto-task state
            PUB._virtualAGV.TargetNode = null;
            PUB._virtualAGV.StopPath();
            PUB.NextWorkCmd = ENIGProtocol.AGVCommandHE.Stop;
            PUB.sm.ClearRunStep();
        }

        private void arLabel4_Click(object sender, EventArgs e)
        {
            //좌회전
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA])
            {
                UTIL.MsgE("자동 충전 중입니다\n충전을 해제 하세요");
                return;
            }
            else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM])
            {
                UTIL.MsgE("수동 충전 중입니다\b충전을 해제 하세요");
                return;
            }
            if (PUB.CheckManualChargeMode() == false) return;
            arDev.Narumi.Speed spd = arDev.Narumi.Speed.Low;
            if (radspdh.Checked) spd = arDev.Narumi.Speed.High;
            else if (radspdl.Checked) spd = arDev.Narumi.Speed.Mid;
            arDev.Narumi.Sensor ss = arDev.Narumi.Sensor.PBSOff;
            if (radpbs0.Checked) ss = arDev.Narumi.Sensor.PBSOn;
            PUB.AGV.AGVMoveManual(arDev.Narumi.ManulOpt.LT, spd, ss);
            PUB.sm.SetNewStep(StateMachine.eSMStep.IDLE);

            // [Manual Safety] Clear previous auto-task state
            PUB._virtualAGV.TargetNode = null;
            PUB._virtualAGV.StopPath();
            PUB.NextWorkCmd = ENIGProtocol.AGVCommandHE.Stop;
            PUB.sm.ClearRunStep();
        }

        private void arLabel11_Click(object sender, EventArgs e)
        {
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA])
            {
                UTIL.MsgE("자동 충전 중입니다\n충전을 해제 하세요");
                return;
            }
            else if (VAR.BOOL[eVarBool.FLAG_CHARGEONM])
            {
                UTIL.MsgE("수동 충전 중입니다\b충전을 해제 하세요");
                return;
            }
            if (PUB.CheckManualChargeMode() == false) return;
            PUB.sm.SetNewStep(StateMachine.eSMStep.IDLE);
            if (PUB.AGV.system1.agv_run == false && PUB.AGV.system1.agv_run_manual == false)
            {
                var dlg = UTIL.MsgQ("자동 진행을 시작할까요?\n우측 옵션을 확인 하세요");
                if (dlg != DialogResult.Yes) return;
                var opt = makeopt();
                if (PUB.AGV.AGVMoveSet(opt) == eNarumiCommandResult.Success)
                    PUB.AGV.AGVMoveRun(opt.Direction == arDev.Narumi.eMoveDir.Forward ? arDev.Narumi.eRunOpt.Forward : arDev.Narumi.eRunOpt.Backward);
            }
            else
            {
                PUB.AGV.AGVMoveStop("fmanual arlabel11_Clcik", arDev.Narumi.eStopOpt.Stop);
            }

        }
        #endregion


        bool tmrun = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Visible == false) return;
            if (tmrun == true) return;
            tmrun = true;

            //충전중이면 수동버튼을 누를수없게한다
            if (VAR.BOOL[eVarBool.FLAG_CHARGEONA] || VAR.BOOL[eVarBool.FLAG_CHARGEONM]) btLeft.Enabled = false;
            else btLeft.Enabled = true;

            btRight.Enabled = btLeft.Enabled;
            btStart.Enabled = btLeft.Enabled;
            btBack.Enabled = btLeft.Enabled;
            btForward.Enabled = btLeft.Enabled;



            //상태메세지
            label1.Text = VAR.STR[eVarString.StatusMessage];

            //마크정보
            guideSensor1.SensorValue = PUB.AGV.data.guidesensor;
            guideSensor1.LMark = PUB.AGV.signal1.mark_sensor_1;
            guideSensor1.RMark = PUB.AGV.signal1.mark_sensor_2;
            guideSensor1.Invalidate();

            if (PUB.AGV.system1.agv_run || PUB.AGV.system1.agv_run_manual)
            {
                btStart.Text = "동작\n멈춤";
                btStart.BackColor = Color.Tomato;
                btStart.BackColor2 = Color.Orange;
            }
            else
            {
                btStart.Text = "자돟\n진행";
                btStart.BackColor = Color.DimGray;
                btStart.BackColor2 = Color.Gray;
            }


            //모터전원상태에따라서 배경색상을 변경해준다.
            //var Mot_Dir_Backward = PUB.AGV.data.Direction == 'B';// PUB.flag.get(EFlag.FLAG_DIR_CW);// PUB.flag.get(EFlag.FLAG_DIR_CW);

            //if (Mot_Dir_Backward == true)
            //{
            //    btBack.BackColor = Color.Lime;
            //    btBack.BackColor2 = Color.Green;

            //    btForward.BackColor = Color.FromArgb(23, 55, 93);
            //    btForward.BackColor2 = Color.FromArgb(12, 36, 64);
            //}
            //else
            //{
            //    btForward.BackColor = Color.Lime;
            //    btForward.BackColor2 = Color.Green;

            //    btBack.BackColor = Color.FromArgb(23, 55, 93);
            //    btBack.BackColor2 = Color.FromArgb(12, 36, 64);
            //}

            tmrun = false;
        }




        private void button1_Click(object sender, EventArgs e)
        {
            PUB.AGV.AGVMoveStop("fmanual button1_click", arDev.Narumi.eStopOpt.MarkStop);
            //VAR.BOOL[eVarBool.FLAG_NEXTSTOP_MARK] = true;


        }

        private void fManual_VisibleChanged(object sender, EventArgs e)
        {
            this.timer1.Enabled = this.Visible;
            if (timer1.Enabled) timer1.Start();
            else timer1.Stop();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            PUB.AGV.AGVErrorReset();
        }

        private void panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        arDev.Narumi.BunkiData makeopt()
        {
            var p = new arDev.Narumi.BunkiData();
            if (radbackward.Checked) p.Direction = arDev.Narumi.eMoveDir.Backward;
            else p.Direction = arDev.Narumi.eMoveDir.Forward;

            if (radleft.Checked) p.Bunki = arDev.Narumi.eBunki.Left;
            else if (radright.Checked) p.Bunki = arDev.Narumi.eBunki.Right;
            else p.Bunki = arDev.Narumi.eBunki.Strate;

            if (radspdh.Checked) p.Speed = arDev.Narumi.eMoveSpd.High;
            else if (radspdl.Checked) p.Speed = arDev.Narumi.eMoveSpd.Low;
            else p.Speed = arDev.Narumi.eMoveSpd.Mid;

            if (radpbs1.Checked) p.PBSSensor = 2;
            else if (radpbs2.Checked) p.PBSSensor = 2;
            else p.PBSSensor = 0;
            return p;
        }

        private void btchargeOff_Click(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("충전 해제 명령을 전송 할까요?") == DialogResult.Yes)
                PUB.AGV.AGVCharge(PUB.setting.ChargerID, false);
        }

        private void btChargeOn_Click(object sender, EventArgs e)
        {
            if (VAR.BOOL[eVarBool.MARK_SENSOR] == false)
            {
                UTIL.MsgE("마크센서가 확인되지 않아 충전을 시작할 수 없습니다");
                return;
            }
            var dlg = UTIL.MsgQ("충전 시작 명령을 전송 할까요?");
            if (dlg != DialogResult.Yes) return;
            PUB.AGV.AGVCharge(PUB.setting.ChargerID, true);
        }

        arDev.Narumi.BunkiData bunkiopt = null;
        private void button1_Click_2(object sender, EventArgs e)
        {
            bunkiopt = makeopt();
            PUB.AGV.AGVMoveSet(bunkiopt);
            PUB.log.Add($"사용자 설정 : {bunkiopt}");
            if (PUB.DriveSpeed)
            {
                if (PUB.AGV.AGVCommand("SSH", PUB.setting.SPD_H.ToString("0000")) == eNarumiCommandResult.Success)
                    PUB.DriveSpeed = false;
            }

        }



        private void arLabel1_Click_1(object sender, EventArgs e)
        {

            if (PUB.AGV.AGVCommand("SSH", PUB.setting.SPD_DRIVE.ToString("0000")) != eNarumiCommandResult.Success)
            {
                AR.UTIL.MsgE("고속속도에 주행속도 연결 실패\n잠시 후 다시 시도하세요");
                return;
            }

            if (this.bunkiopt == null) bunkiopt = makeopt();
            bunkiopt.Speed = arDev.Narumi.eMoveSpd.High;
            if (PUB.AGV.AGVMoveSet(bunkiopt) == eNarumiCommandResult.Success)
            {
                PUB.log.Add($"고속주행설정 : {bunkiopt}");
                PUB.DriveSpeed = true;

                AR.UTIL.MsgI($"주행속도({PUB.setting.SPD_DRIVE})가 '고속' 속도에 연결되었습니다.\n" +
                    $"창을 이동하거나 '설정적용'을 누르면 원래속도({PUB.setting.SPD_H})로 변경 됩니다");
            }
            else
            {
                UTIL.MsgE($"고속 속도 설정이 실패되었습니다");
            }
        }

        private void btLeft180_Click(object sender, EventArgs e)
        {
            //[STX]		C	T	L	0	0	0	0	A	3	[ETX]
            PUB.AGV.AGVMoveLeft180Turn();

        }

        private void btRight180_Click(object sender, EventArgs e)
        {
            //[STX]		C	T	R	0	0	0	0	A	9	[ETX]
            PUB.AGV.AGVMoveRight180Turn();
        }

        private void btBack180_Click(object sender, EventArgs e)
        {
            //[STX]		C	T	B	0	0	0	0	9	9	[ETX]
            PUB.AGV.LiftControl(LiftCommand.ON);// (;// (true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PUB.AGV.LiftControl(LiftCommand.OFF);
        }
    }
}
