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 arDev.AzinAxt;
using arDev.AzinAxt.Emulator;

namespace Project.Dialog
{
    public partial class fEmulator : Form
    {
        public arDev.AzinAxt.Emulator.CEmulMOT devM { get; private set; }
        public arDev.AzinAxt.Emulator.CEmuleDIO devIO { get; private set; }

        int axcount { get { return devM.axisCount; } }

        JogController[] jobCtl;

        public fEmulator(arDev.AzinAxt.MOT mot, int motCnt, int cntDI, int cntDO)
        {
            InitializeComponent();

            devM = new CEmulMOT(motCnt);
            devM.TimerInterval = 50;

            devIO = new CEmuleDIO(cntDI, cntDO);
            devIO.IOValueChagned += Dev_IOValueChagned;

            Pub.flag.ValueChanged += Flag_ValueChanged;

            //motion
            this.jobCtl = new JogController[] { jog1, jog2, jog3, jog4, jog5, jog6, jog7 };

            foreach (var item in jobCtl)
            {
                item.arDebugMode = false;
                //item.ItemClick += Item_ItemClick;
            }

            for (int i = 0; i < motCnt; i++)
            {
                Boolean enb = i < motCnt;
                jobCtl[i].MotionObject = mot;
                jobCtl[i].Enabled = enb;
                jobCtl[i].arUsage = enb;
                jobCtl[i].arAutoUpdate = false;                
                jobCtl[i].Invalidate();

                if (enb)
                {
                    devM.MaxPosition[i] = jobCtl[i].arMaxLength;
                    devM.MinPosition[i] = jobCtl[i].arMinLength;
                }
            }

            //i/o
            this.tblDI.SuspendLayout();
            this.tblDO.SuspendLayout();

            var pinNameI = new string[cntDI];
            var pinNameO = new string[cntDO];
            var pinTitleI = new string[cntDI];
            var pinTitleO = new string[cntDO];

            for (int i = 0; i < pinNameI.Length; i++)
            {
                pinNameI[i] = "X" + i.ToString("X2").PadLeft(3, '0');// Enum.GetName(typeof(ePLCIPin), i); //Enum.GetNames(typeof(eDIName))[i];// i.ToString();
                pinTitleI[i] = string.Empty;// i.ToString();// Enum.GetName(typeof(ePLCITitle), i); //Enum.GetNames(typeof(eDITitle))[i];

            }

            for (int i = 0; i < pinNameO.Length; i++)
            {
                pinNameO[i] = "Y" + i.ToString("X2").PadLeft(3, '0');// Enum.GetName(typeof(ePLCOPin), i); // Enum.GetNames(typeof(eDOName))[i];
                pinTitleO[i] = string.Empty;//i.ToString();// Enum.GetName(typeof(ePLCOTitle), i); // Enum.GetNames(typeof(eDOTitle))[i];
            }

            tblDI.MatrixSize = new Point(8, 8);
            tblDO.MatrixSize = new Point(8, 8);

            tblDI.setTitle(pinTitleI);
            tblDO.setTitle(pinTitleO);

            tblDI.setNames(pinNameI);
            tblDO.setNames(pinNameO);

            tblDI.setItemTextAlign(ContentAlignment.BottomLeft);
            tblDO.setItemTextAlign(ContentAlignment.BottomLeft);

            tblDI.setValue(devIO.Input);
            tblDO.setValue(devIO.Output);

            //dio.IOValueChanged += dio_IOValueChanged;

            this.tblDI.ItemClick += tblDI_ItemClick;
            this.tblDO.ItemClick += tblDO_ItemClick;

            this.tblDI.Invalidate();
            this.tblDO.Invalidate();

            
        }


        private void fEmulator_Load(object sender, EventArgs e)
        {
            this.ctlContainer1.setDevice(this.devIO, this.devM);
            timer1.Start();
            this.toolStripStatusLabel1.Text = "Top Most :" + (this.TopMost ? "On" : "Off");
        }
        void tblDO_ItemClick(object sender, GridView.ItemClickEventArgs e)
        {
            var nVal = !devIO.Output[e.idx];//.Get(e.idx);// doValue[e.idx];// == 1 ? (ushort)0 : (ushort)1;
            devIO.SetOutput(e.idx, nVal);
        }
        void tblDI_ItemClick(object sender, GridView.ItemClickEventArgs e)
        {
            var nVal = !devIO.Input[e.idx];
            devIO.SetInput(e.idx, nVal);
        }
        private void Flag_ValueChanged(object sender, CInterLock.ValueEventArgs e)
        {
            var fg = (eFlag)e.ArrIDX;
        }
        private void Dev_IOValueChagned(object sender, CEmuleDIO.IOValueChangedArgs e)
        {
            if (e.Dir == CEmuleDIO.eDirection.In)
            {
                if (e.ArrIDX == (int)eDIName.BUT_STARTF && e.NewValue)
                {
                    this.devIO.SetInput((int)eDIName.PORT0_DET_UP, false);
                    this.devIO.SetInput((int)eDIName.PORT1_DET_UP, false);
                    this.devIO.SetInput((int)eDIName.PORT2_DET_UP, false);
                }
                else if (e.ArrIDX == (int)eDIName.BUT_RESETF && e.NewValue)
                {
                    this.devIO.SetInput((int)eDIName.PORT0_DET_UP, false);
                    this.devIO.SetInput((int)eDIName.PORT1_DET_UP, false);
                    this.devIO.SetInput((int)eDIName.PORT2_DET_UP, false);
                }

                //해당 아이템의 값을 변경하고 다시 그린다.
                if (tblDI.setValue(e.ArrIDX, e.NewValue))
                    tblDI.Invalidate();//.drawItem(e.ArrIDX);
                Console.WriteLine(string.Format("di change {0}:{1}", e.ArrIDX, e.NewValue.ToString()));
            }
            else
            {
                //sir sol값에따라서 감지 센서를 연동
                if (e.ArrIDX == (int)eDOName.SOL_AIR) this.devIO.SetInput((int)eDIName.AIR_DETECT, e.NewValue);
                //else if (e.ArrIDX == (int)eDOName.PICKF_VAC1 && e.NewValue == false) this.devIO.SetInput((int)eDIName.pick, e.NewValue);  //진공이켜지만 아이템이 감지된걸로 한다
                //else if (e.ArrIDX == (int)eDOName.PICKF_VAC2 && e.NewValue == false) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK2, e.NewValue);
                //else if (e.ArrIDX == (int)eDOName.PICKF_VAC3 && e.NewValue == false) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK3, e.NewValue);
                //else if (e.ArrIDX == (int)eDOName.PICKF_VAC4 && e.NewValue == false) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK4, e.NewValue);

                //해당 아이템의 값을 변경하고 다시 그린다.
                if (tblDO.setValue(e.ArrIDX, e.NewValue))
                    tblDO.Invalidate();//.drawItem(e.ArrIDX);

                //모터가 run 되면 몇초있다가 꺼야하낟.
                if (e.ArrIDX == (int)eDOName.PORT0_MOT_RUN)
                {
                    MotorRunStart[0] = DateTime.Now;
                }
                else if (e.ArrIDX == (int)eDOName.PORT1_MOT_RUN)
                {
                    MotorRunStart[1] = DateTime.Now;
                }
                else if (e.ArrIDX == (int)eDOName.PORT2_MOT_RUN)
                {
                    MotorRunStart[2] = DateTime.Now;
                }
                else if (e.ArrIDX == (int)eDOName.PORT0_MOT_DIR)
                {
                    MotorRunStart[0] = DateTime.Now;
                }
                else if (e.ArrIDX == (int)eDOName.PORT1_MOT_DIR)
                {
                    MotorRunStart[1] = DateTime.Now;
                }
                else if (e.ArrIDX == (int)eDOName.PORT2_MOT_DIR)
                {
                    MotorRunStart[2] = DateTime.Now;
                }


                Console.WriteLine(string.Format("do change {0}:{1}", e.ArrIDX, e.NewValue.ToString()));
            }
        }

        DateTime[] MotorRunStart = new DateTime[] { DateTime.Now,DateTime.Now,DateTime.Now };

        Boolean CheckTime(DateTime Start, int ElapSecond)
        {
            var ts = DateTime.Now - Start;
            if (ts.TotalSeconds >= ElapSecond) return true;
            else return false;
               
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < axcount; i++)
            {
                //각 축별 데이터를 표시한다
                this.jobCtl[i].arIsOrg = devM.isOrg(i);
                this.jobCtl[i].arIsInp = devM.isINp(i);
                this.jobCtl[i].arIsAlm = devM.isAlm(i);
                this.jobCtl[i].arIsLimN = devM.isLimM(i);
                this.jobCtl[i].arIsLimP = devM.isLimP(i);
                this.jobCtl[i].arIsSvON = devM.isSvOn(i);

                this.jobCtl[i].ardAct = devM.dAct[i];
                this.jobCtl[i].ardCmd = devM.dCmd[i];
                this.jobCtl[i].arIsInit = true;// MotionObject.IsInit;
                //this.jobCtl[i].arIsHSet = devM.isHSet[i];

                this.jobCtl[i].Invalidate();
            }


            //포트용 모터가 켜져잇으ㅜ면 detect 작업을 자동으로 해준다
            if(checkBox1.Checked)
            {
                if (Util_DO.GetIOOutput(eDOName.PORT0_MOT_RUN))  //역방향으로 모터가 가동 중이다
                {
                    if (Util_DO.GetPortMotorDir(0) == eMotDir.CCW && CheckTime(MotorRunStart[0], 7))
                        devIO.SetInput((int)eDIName.PORT0_LIM_DN, true);
                    if (Util_DO.GetPortMotorDir(0) == eMotDir.CCW && CheckTime(MotorRunStart[0], 1))
                        devIO.SetInput((int)eDIName.PORT0_DET_UP, false);

                    if (Util_DO.GetPortMotorDir(0) == eMotDir.CW && CheckTime(MotorRunStart[0], 5))
                        devIO.SetInput((int)eDIName.PORT0_DET_UP, true);
                    if (Util_DO.GetPortMotorDir(0) == eMotDir.CW && CheckTime(MotorRunStart[0], 3))
                        devIO.SetInput((int)eDIName.PORT0_LIM_DN, false);
                }
                if (Util_DO.GetIOOutput(eDOName.PORT1_MOT_RUN))   //역방향으로 모터가 가동 중이다
                {
                    if (Util_DO.GetPortMotorDir(1) == eMotDir.CCW && CheckTime(MotorRunStart[1], 7))
                        devIO.SetInput((int)eDIName.PORT1_LIM_DN, true);
                    if (Util_DO.GetPortMotorDir(1) == eMotDir.CCW && CheckTime(MotorRunStart[1], 1))
                        devIO.SetInput((int)eDIName.PORT1_DET_UP, false);

                    if (Util_DO.GetPortMotorDir(1) == eMotDir.CW && CheckTime(MotorRunStart[1], 5))
                        devIO.SetInput((int)eDIName.PORT1_DET_UP, true);
                    if (Util_DO.GetPortMotorDir(1) == eMotDir.CW && CheckTime(MotorRunStart[1], 3))
                        devIO.SetInput((int)eDIName.PORT1_LIM_DN, false);
                }
                if (Util_DO.GetIOOutput(eDOName.PORT2_MOT_RUN)) //역방향으로 모터가 가동 중이다
                {
                    if (Util_DO.GetPortMotorDir(2) == eMotDir.CCW && CheckTime(MotorRunStart[2], 7))
                        devIO.SetInput((int)eDIName.PORT2_LIM_DN, true);
                    if (Util_DO.GetPortMotorDir(2) == eMotDir.CCW && CheckTime(MotorRunStart[2], 1))
                        devIO.SetInput((int)eDIName.PORT2_DET_UP, false);

                    if (Util_DO.GetPortMotorDir(2) == eMotDir.CW && CheckTime(MotorRunStart[2], 5))
                        devIO.SetInput((int)eDIName.PORT2_DET_UP, true);
                    if (Util_DO.GetPortMotorDir(2) == eMotDir.CW && CheckTime(MotorRunStart[2], 3))
                        devIO.SetInput((int)eDIName.PORT2_LIM_DN, false);
                }
            }
            //if (Util_DO.GetPortMotorDir(0) == eMotDir.CW && Util_DO.GetIOOutput(eDOName.PORT0_MOT_RUN) == true && checkBox1.Checked)
            //    this.devIO.SetInput((int)eDIName.PORT1_DET_UP, true);

            //if (Util_DO.GetPortMotorDir(1) == eMotDir.CW && Util_DO.GetIOOutput(eDOName.PORT1_MOT_RUN) == true && checkBox1.Checked)
            //    this.devIO.SetInput((int)eDIName.PORT2_DET_UP, true);


            //백큠을 집는 행동 처리
            if (Pub.sm.Step == StateMachine.eSMStep.RUN)
            {
                //ZL이 집는 위치일경우
                if (Util_Mot.GetPKX_PosName() == ePickYPosition.PICKON)
                {
                    if (checkBox2.Checked)
                    {
                        //if (devIO.Output[(int)eDOName.PICKF_VAC1]) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK1, true);
                        //if (devIO.Output[(int)eDOName.PICKF_VAC2]) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK2, true);
                        //if (devIO.Output[(int)eDOName.PICKF_VAC3]) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK3, true);
                        //if (devIO.Output[(int)eDOName.PICKF_VAC4]) this.devIO.SetInput((int)eDIName.PICKF_VAC_CHK4, true);
                    }
                }
            }

            //그룹박스내의 센서류 업데이트 
            this.ctlContainer1.updateControl();

        }



        private void toolStripButton1_Click(object sender, EventArgs e)
        {

            Pub.mot.SetSVON(true);

            //emg on
            devIO.SetInput((int)eDIName.BUT_EMGF, false);
           // devIO.SetInput((int)eDIName.PICKF_OVERLOAD, true);
            //devIO.SetInput((int)eDIName.PICKR_OVERLOAD, true);

            SLLimP.arPin.PinIndex = (int)eDIName.PORT1_LIM_UP;
            SLDetU.arPin.PinIndex = (int)eDIName.PORT1_DET_UP;
            SLLimN.arPin.PinIndex = (int)eDIName.PORT1_LIM_DN;

            SRLimP.arPin.PinIndex = (int)eDIName.PORT2_LIM_UP;
            SRDetU.arPin.PinIndex = (int)eDIName.PORT2_DET_UP;
            SRLimN.arPin.PinIndex = (int)eDIName.PORT2_LIM_DN;

            //타워램프   
            ctlTowerLamp1.arPinRed.PinIndex = (int)eDOName.TWR_REDF;
            ctlTowerLamp1.arPinYel.PinIndex = (int)eDOName.TWR_YELF;
            ctlTowerLamp1.arPinGrn.PinIndex = (int)eDOName.TWR_GRNF;
            ctlTowerLamp1.arPinBuz.PinIndex = (int)eDOName.BUZZER;
            ctlTowerLamp1.arPinRed.Output = true;
            ctlTowerLamp1.arPinYel.Output = true;
            ctlTowerLamp1.arPinGrn.Output = true;

            //전면조작버  
            sf1.arPin.PinIndex = (int)eDOName.SOL_AIR;
            sf2.arPin.PinIndex = (int)eDOName.BUT_STARTF;
            sf3.arPin.PinIndex = (int)eDOName.BUT_STOPF;
            sf4.arPin.PinIndex = (int)eDOName.BUT_RESETF;
            sf1.arPin.Output = true;
            sf2.arPin.Output = true;
            sf3.arPin.Output = true;
            sf4.arPin.Output = true;

            //모터구동
            m1.Pin_Run.PinIndex = (int)eDOName.PORT0_MOT_RUN;
            m2.Pin_Run.PinIndex = (int)eDOName.PORT1_MOT_RUN;
            m1.Pin_Run.Output = true;
            m2.Pin_Run.Output = true;

            devIO.SetOutput((int)eDOName.SOL_AIR, true);


        }



        private void btAir_MouseDown(object sender, MouseEventArgs e)
        {
            var bt = sender as UIControl.CtlSensor;
            switch (bt.Text.ToLower())
            {
                case "air":
                    devIO.SetInput((int)eDIName.BUT_AIRF, true);
                    break;
                case "stop":
                    devIO.SetInput((int)eDIName.BUT_STOPF, true);
                    break;
                case "reset":
                    devIO.SetInput((int)eDIName.BUT_RESETF, true);
                    break;
                case "start":
                    devIO.SetInput((int)eDIName.BUT_STARTF, true);
                    break;
            }
        }

        private void btAir_MouseUp(object sender, MouseEventArgs e)
        {
            var bt = sender as UIControl.CtlSensor;
            switch (bt.Text.ToLower())
            {
                case "air":
                    devIO.SetInput((int)eDIName.BUT_AIRF, false);
                    break;
                case "stop":
                    devIO.SetInput((int)eDIName.BUT_STOPF, false);
                    break;
                case "reset":
                    devIO.SetInput((int)eDIName.BUT_RESETF, false);
                    break;
                case "start":
                    devIO.SetInput((int)eDIName.BUT_STARTF, false);
                    break;
            }
        }

        private void m1_Click(object sender, EventArgs e)
        {
            var cur = devIO.Output[(int)eDOName.PORT0_MOT_RUN];
            devIO.SetOutput((int)eDOName.PORT0_MOT_RUN, !cur);
        }

        private void m2_Click(object sender, EventArgs e)
        {
            var cur = devIO.Output[(int)eDOName.PORT1_MOT_RUN];
            devIO.SetOutput((int)eDOName.PORT1_MOT_RUN, !cur);
        }

        private void SLLimP_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT1_LIM_UP];
            devIO.SetInput((int)eDIName.PORT1_LIM_UP, !cur);
        }

        private void SRLimP_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT2_LIM_UP];
            devIO.SetInput((int)eDIName.PORT2_LIM_UP, !cur);
        }

        private void SLDetU_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT1_DET_UP];
            devIO.SetInput((int)eDIName.PORT1_DET_UP, !cur);
        }

        private void SRDetU_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT2_DET_UP];
            devIO.SetInput((int)eDIName.PORT2_DET_UP, !cur);
        }

        private void SLLimN_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT1_LIM_DN];
            devIO.SetInput((int)eDIName.PORT1_LIM_DN, !cur);
        }

        private void SRLimN_Click(object sender, EventArgs e)
        {
            var cur = devIO.Input[(int)eDIName.PORT2_LIM_DN];
            devIO.SetInput((int)eDIName.PORT2_LIM_DN, !cur);
        }


        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            devM.TimerInterval = 50;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            devM.TimerInterval = 100;
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            devM.TimerInterval = 10;
        }
    }
}
