using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using static Project.StateMachine;

namespace Project
{
    public partial class fMain
    {
        private void ColorChangeMotionST(arCtl.arLabel ctl, Color c, Boolean isvalue)
        {
            if (isvalue)
            {
                int r = c.R + 100;
                int g = c.G + 100;
                int b = c.B + 100;
                if (r > 255) r = 255;
                if (g > 255) g = 255;
                if (b > 255) b = 255;
                if (r < 0) r = 0;
                if (g < 0) g = 0;
                if (b < 0) b = 0;
                ctl.BackColor = Color.FromArgb(r, g, b);
                ctl.BackColor2 = c;
            }
            else
            {
                ctl.BackColor = Color.FromArgb(100, 100, 100);
                ctl.BackColor2 = Color.FromArgb(90, 90, 90);
            }
        }

        private void BCDHWStatus(Boolean enable, arCtl.arLabel ctl, bool isReady)
        {
            if (enable == false)
            {
                ctl.BackColor2 = Color.Gray;
            }
            else
            {
                if (isReady)
                {
                    ctl.BackColor2 = Color.SeaGreen;
                }
                else
                {
                    if (ctl.BackColor2 == Color.Tomato)
                    {
                        ctl.BackColor2 = Color.Gray;
                    }
                    else
                    {
                        ctl.BackColor2 = Color.Tomato;
                    }
                }
            }
        }


        void BlinkHwstatus(int row, int col, int value1, int value2)
        {
            var curValue = HWState.getValue(row, col);
            HWState.setValue(row, col, (byte)(curValue == value1 ? value2 : value1)); // 
        }

        Boolean displayOn = false;
        private void tmDisplay_Tick(object sender, EventArgs e)
        {
            if (displayOn == false) displayOn = true;
            else
            {
                Pub.log.AddAT("Display Timer Overlab");// Console.WriteLine("display overlab");
                return;
            }

            if (Pub.sm.Step > eSMStep.INIT &&
                panTopMenu.Enabled == false) panTopMenu.Enabled = true;


            //쓰레드로인해서 메인에서 진행하게한다. SPS는 메인쓰레드에서 진행 됨
            //팝을 제거 혹은 표시하는 기능
            if (Pub.popup.needShow) Pub.popup.showMessage();
            else if (Pub.popup.needClose) Pub.popup.Visible = false; // .setVision(false)();

            lbTime.Text = Pub.sm.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss");

            //상태 표시
            Update_SSStatus();

            //H/W 상태표시
            Update_HWStatus();

            //IO상태(상단줄) 표시
            Update_IOStatus();

            //display mesasge
            UpdateResultMessage();


            //메세지창이 깜박거려야하는 상황 체크
            if (lbMsg.Tag != null)
            {
                var bg1 = lbMsg.BackColor;
                var bg2 = lbMsg.BackColor2;
                lbMsg.BackColor = bg2;
                lbMsg.BackColor2 = bg1;
                lbMsg.Invalidate();
            }




            HWState.Invalidate();
            SSInfo.Invalidate();
            IOState.Invalidate();

            #region retgion"1분 time 루틴"
            var ts = DateTime.Now - tm1minute;
            if (ts.TotalMinutes >= 1)
            {
                //리셋카운트
                _AutoResetCount();
                tm1minute = DateTime.Now;
            }
            #endregion

            #region retgion"5분 time 루틴"
            ts = DateTime.Now - tm5minute;
            if (ts.TotalMinutes >= 5)
            {
                //남은디스크확인
                CheckFreeSpace();
                tm5minute = DateTime.Now;
            }
            #endregion

            //wat.Stop();
            //Console.WriteLine("disp time : " + wat.ElapsedMilliseconds.ToString() + "ms");
            displayOn = false;
        }

        void Update_IOStatus()
        {
            int inputrow = 1;
            int inputcol = 0;
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.VS_READY) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.VS_OK) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.VS_ERR) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.VS_COMPLETE) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.VS_LOTEND) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);

            var numver_mz = Pub.plc1.getValue<UInt16>(7902);
            var numver_sn = Pub.plc1.getValue<UInt16>(7903);
            var bin_mz = Convert.ToString(numver_mz, 2).PadLeft(16,'0');
            var bin_sn = Convert.ToString(numver_sn, 2).PadLeft(16, '0');
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);

            inputrow = 0;
            inputcol = 0;
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.MC_START) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.MC_CONFIRM) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, (ushort)(Pub.plc1.getValue(7900, (int)eDIName.MC_LOTEND) ? 1 : 0));
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0);
            IOState.setTitle(inputrow, inputcol, "--"); IOState.setValue(inputrow, inputcol++, 0); 

            //IOState.setTitle(0, inputcol, "DOOR"); IOState.setValue(0, inputcol++, (ushort)(Util_DO.CheckDoorSafty() ? 1 : 2));
            //IOState.setTitle(0, inputcol, "SAFTY"); IOState.setValue(0, inputcol++, (ushort)(Pub.flag.get(eFlag.MGZSafty1) && Pub.flag.get(eFlag.MGZSafty2) ? 1 : 2));
            //IOState.setTitle(0, inputcol, "FULL"); IOState.setValue(0, inputcol++, (ushort)(Util_DO.GetIOInput(eDIName.UD_FULL) ? 2 : 0));

            //IOState.setTitle(0, inputcol, "A/B\nDETECT"); IOState.setValue(0, inputcol++, (ushort)(Util_DO.GetIOInput(eDIName.AB_DETECT) ? 1 : 0));

        }
        void Update_SSStatus()
        {
            SSInfo.setTitle(0, 0, Pub.sm.Step.ToString());
            SSInfo.setTitle(1, 0, Pub.sm.runStep.ToString());
            if (Pub.sm.Step == eSMStep.RUN)
                SSInfo.setTitle(1, 1, string.Format("{0:N1} sec", Pub.sm.getRunSteptime.TotalSeconds));
            else
                SSInfo.setTitle(1, 1, "--");

        }
        void Update_HWStatus()
        {
            var rownum = 1;
            var colIdx = 0;
            //if (Pub.light.IsInit == false) BlinkHwstatus(rownum, colIdx++, 3, 4);
            //else HWState.setValue(rownum, colIdx++, (byte)(Pub.light.IsInit ? 2 : 3)); // 

            if (Pub.plc1.IsValid == false) BlinkHwstatus(rownum, colIdx++, 3, 4);
            else HWState.setValue(rownum, colIdx++, (byte)(Pub.plc1.IsValid ? 2 : 3)); //PLC

            if (Pub.Xbee.IsInit == false) BlinkHwstatus(rownum, colIdx++, 3, 4);
            else HWState.setValue(rownum, colIdx++, (byte)(Pub.Xbee.IsInit ? 2 : 3)); // 

            //if (Pub.camera.IsInit == false) BlinkHwstatus(rownum, colIdx++, 3, 4);
            //else HWState.setValue(rownum, colIdx++, (byte)(Pub.camera.IsInit ? 2 : 3)); //

            //if (Pub.bVisionLicense == false) BlinkHwstatus(rownum, colIdx++, 3, 4);
            //else HWState.setValue(rownum, colIdx++, (byte)(Pub.bVisionLicense ? 2 : 3)); //

        }

        /// <summary>
        /// 환경설정에따른 카운트를 리셋처리한다. 171128
        /// </summary>
        void _AutoResetCount()
        {
            if (Pub.setting.datetime_Check_1 && Pub.setting.datetime_Reset_1 != "") //오전
            {
                try
                {
                    DateTime SetTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + Pub.setting.datetime_Reset_1 + ":00");
                    DateTime LastClearTime = Pub.counter.CountReset;

                    //현재 시간이 클리어대상 시간보다 크고, 마지막으로 클리어한 시간이 지정시간보다 작아야함
                    if (DateTime.Now > SetTime && LastClearTime < SetTime)
                    {
                        Pub.log.AddI("Count Reset #1");
                        Pub.counter.CountClear();
                    }
                }
                catch { }
            }

            if (Pub.setting.datetime_Check_2 && Pub.setting.datetime_Reset_2 != "") //오후
            {
                try
                {
                    DateTime SetTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + Pub.setting.datetime_Reset_2 + ":00");
                    DateTime LastClearTime = Pub.counter.CountReset;

                    //현재 시간이 클리어대상 시간보다 크고, 마지막으로 클리어한 시간이 지정시간보다 작아야함
                    if (DateTime.Now > SetTime && LastClearTime < SetTime)
                    {
                        Pub.log.AddI("Count Reset #2");
                        Pub.counter.CountClear();
                    }
                }
                catch { }
            }
        }

        DateTime tm1minute = DateTime.Now.AddDays(-1);
        DateTime tm5minute = DateTime.Now;

        void UpdateProgressStatus(string title, double value, double max)
        {
            UpdateProgressStatus((float)value, (float)max, title);
        }

        void UpdateProgressStatus(float value, float max, string title)
        {
            if (lbMsg.ProgressEnable == false) lbMsg.ProgressEnable = true;
            if (lbMsg.ProgressMax != max) lbMsg.ProgressMax = max;
            if (lbMsg.ProgressValue != value) lbMsg.ProgressValue = value;
            if (lbMsg.ProgressForeColor != Color.FromArgb(40, 40, 40))
                lbMsg.ProgressForeColor = Color.FromArgb(40, 40, 40);
            if (lbMsg.Text != title) lbMsg.Text = title;
        }

        void UpdateStatusMessage(string dispmsg, Color fcolor, Color shadow)
        {
            UpdateStatusMessage(dispmsg, Color.DimGray, Color.Gray, fcolor, shadow);
        }

        void UpdateStatusMessage(string dispmsg, Color bColor, Color bColor2, Color fcolor, Color shadow, Boolean blank = false)
        {

            //if (lbMsg.ProgressEnable == true) lbMsg.ProgressEnable = false;
            if (dispmsg != lbMsg.Text || lbMsg.ForeColor != fcolor || lbMsg.ShadowColor != shadow || (lbMsg.BackColor != bColor && lbMsg.BackColor2 != bColor))
            {
                lbMsg.BackColor = bColor;
                lbMsg.BackColor2 = bColor2;
                lbMsg.ForeColor = fcolor;
                lbMsg.ShadowColor = shadow;
                lbMsg.Text = dispmsg;
                if (blank) lbMsg.Tag = "BLANK";
                else lbMsg.Tag = null;
            }
        }


        void UpdateResultMessage()
        {
            //모션을 사용한다면 홈 검색여부를 확인한다.

            //var inspresult = "";
            //if (Pub.Result == null || Pub.Result.Result == CResult.eInspectResult.NOTSET)
            //    inspresult = "--";
            //else if (Pub.Result.Result == CResult.eInspectResult.OK)
            //    inspresult = "MATCH";
            //else if (Pub.Result.Result == CResult.eInspectResult.NG)
            //    inspresult = "MISMATCH";


            //최우선 점검 사항 표시
            if (Pub.sm.Step > eSMStep.INIT)
            {
                if (Pub.flag.get(eFlag.DemoRun))
                {
                    UpdateStatusMessage("DEMO RUN", Color.Gold, Color.Yellow, Color.Black, Color.WhiteSmoke, true);
                }

              
                else if (Pub.flag.get(eFlag.START) == true)
                {
                    UpdateStatusMessage("매거진투입구 안전센서 감지", Color.Tomato, Color.Black);
                }
                else if (Pub.Result.Model.Title == "")
                {
                    UpdateStatusMessage("비젼모델 선택이 필요함", Color.Tomato, Color.Black);
                }

                if (Pub.sm.Step == eSMStep.IDLE)
                {
                    UpdateStatusMessage("준비완료", Color.Lime, Color.Black);
                }
                else if (Pub.sm.Step == eSMStep.ERROR)
                {
                    UpdateStatusMessage("오류 발생", Color.Red, Color.Black);
                }
                else if (Pub.sm.Step == eSMStep.PAUSE)
                {
                    UpdateStatusMessage("정지 됨", Color.Tomato, Color.Black);
                }
                else if (Pub.sm.Step == eSMStep.FINISH)
                    UpdateStatusMessage("작업 완료", Color.Lime, Color.Black);
                else if (Pub.sm.bPause == true)
                {
                    UpdateStatusMessage("[START]를 누르면 시작 됩니다", Color.Yellow, Color.Black);
                }
                else if (Pub.flag.get(eFlag.TestRun))
                {
                    UpdateStatusMessage("TEST RUN", Color.DeepSkyBlue, Color.LightSkyBlue, Color.Blue, Color.WhiteSmoke, true);
                }
                else
                {

                    string msg = "진행중";
                    UpdateStatusMessage(msg, Color.Lime, Color.Black);
                }
            }
        }
    }
}
