using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AR;

namespace Project
{
    public partial class FMain
    {
        /// <summary>
        /// Automatic message change for status display labels
        /// </summary>
        /// <param name="idx"></param>
        void UpdateStatusMessage()
        {
            arCtl.arLabel lbl = lbMsg;

            //Check if message window should blink
            if (lbl.Tag != null && lbl.Tag.ToString() == "BLINK")
            {
                var bg1 = lbl.BackColor;
                var bg2 = lbl.BackColor2;
                 if(bg2 != null) lbl.BackColor = (Color)bg2;
                lbl.BackColor2 = bg1;
                lbl.Invalidate();
            }

            if (PUB.sm.Step == eSMStep.INIT)
            {
                SetStatusMessage("Initialization in progress", Color.White, Color.FromArgb(0x38, 0x4d, 0x9d));
            }
            else if (PUB.sm.Step == eSMStep.IDLE)
            {
                //Check various I/O and display error messages

                var msg = string.Empty;
                bool errst = true;
                if (PUB.mot.IsInit == false) msg = "Motion card not ready";
                else if (PUB.dio.IsInit == false) msg = "I/O card not ready";
                else if (PUB.dio.HasDIOn == false) msg = "Power check required (input port not detected)";
                else if (PUB.mot.HasServoAlarm == true) msg = "Servo alarm occurred";
                else if (PUB.mot.HasHoming == true) msg = "Home search in progress";
                else if (PUB.mot.HasServoOff == true) msg = "Servo OFF occurred";
                else if (DIO.GetIOOutput(eDOName.SOL_AIR) == false) msg = "AIR output failed (Press the front blue AIR button)";
                else if (DIO.GetIOInput(eDIName.AIR_DETECT) == false) msg = "AIR not detected";
                else if (DIO.isSaftyDoorF() == false) msg = "Front Door Safty Error";
                else if (DIO.isSaftyDoorR() == false) msg = "Rear Door Safty Error";
                else if (PUB.mot.HasHomeSetOff == true)
                {
                    if (DIO.GetIOInput(eDIName.PICKER_SAFE) == false)
                    {
                        msg = "Please move the picker (X) axis to center (Function-Management screen)";
                    }
                    else
                    {
                        msg = "Home search is required";
                    }

                }
                else
                {

                    var limport = new List<string>();
                    if (PUB.mot.HasLimitError == true)
                    {
                        for (short i = 0; i < SETTING.System.MotaxisCount; i++)
                        {
                            if (PUB.mot.IsUse(i) == false) continue;
                            if (PUB.mot.IsLimitN(i))
                            {
                                var useOrgSensor = PUB.system_mot.GetUseOrigin;
                                if (useOrgSensor[i] == true) limport.Add(i.ToString());
                            }
                            else if (PUB.mot.IsLimitP(i))
                                limport.Add(i.ToString());
                            else if (PUB.mot.IsLimitSWN(i))
                                limport.Add(i.ToString());
                            else if (PUB.mot.IsLimitSWP(i))
                                limport.Add(i.ToString());
                        }
                    }
                    if (limport.Any())
                    {
                        msg = "Servo LIMIT alarm occurred (Ax:" + string.Join(",", limport) + ")";
                    }
                    else
                    {
                        msg = "Press START to begin operation";
                        errst = false;
                    }


                }

                if (errst)
                {
                    SetStatusMessage(msg, Color.White, Color.Red, Color.IndianRed, Color.DimGray, blank: true);
                }
                else
                {
                    Color fColor = Color.FromArgb(200, 200, 200);
                    Color bColor1 = Color.DimGray;
                    Color bColor2 = Color.DarkGray;

                    SetStatusMessage(msg, Color.Lime, bColor1, bColor2, Color.Black, true);
                }

            }

            else if (PUB.sm.Step == eSMStep.WAITSTART)
            {
                SetStatusMessage("[Waiting to Start] ", Color.Gold, Color.FromArgb(50, 50, 50));
            }
            else if (PUB.sm.Step == eSMStep.ERROR)
            {
                var msglis = PUB.Result.ResultMessage.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                SetStatusMessage($"{msglis[0]}", Color.White, Color.Red);
            }
            else if (PUB.sm.Step == eSMStep.PAUSE)
            {
                SetStatusMessage("[Paused] ", Color.Gold, Color.FromArgb(50, 50, 50));
            }
            else if (PUB.sm.Step == eSMStep.HOME_FULL)// || Pub.sm.Step == eSMStep.QHOME)
            {
                SetStatusMessage($"Checking home position of all motion axes", Color.White, Color.FromArgb(0x98, 0x79, 0xd0), shadow: Color.DimGray);
            }
            else if (PUB.sm.Step == eSMStep.HOME_DELAY)// || Pub.sm.Step == eSMStep.QHOME)
            {
                SetStatusMessage($"Please wait a moment (homing in progress)", Color.White, Color.FromArgb(0x98, 0x79, 0xd0), shadow: Color.DimGray);
            }
            else if (PUB.sm.Step == eSMStep.HOME_CONFIRM)// || Pub.sm.Step == eSMStep.QHOME)
            {
                SetStatusMessage($"Completing home operation", Color.White, Color.FromArgb(0x98, 0x79, 0xd0), shadow: Color.DimGray);
            }
            else if (PUB.sm.Step == eSMStep.RUN)
            {

                double cur = PUB.sm.seq.GetTime(PUB.sm.Step).TotalSeconds;
                double max = AR.SETTING.Data.Timeout_StepMaxTime;
                string msg = $"In Progress";
                Color fColor = Color.Gold;

                if (PUB.flag.get(eVarBool.FG_JOB_END))
                {
                    msg = "Loader is empty. Operation will be completed shortly";
                    cur = max = 0;
                    fColor = Color.Lime;

                }
                else if (PUB.flag.get(eVarBool.FG_WAIT_LOADERINFO))
                {
                    msg = "Waiting for user information input";
                    cur = 100;
                    max = 100;
                }
                else //if (PUB.flag.get(eVarBool.RDY_VISION1) == true && PUB.flag.get(eVarBool.RDY_PORT_PC) == true && idx == 9)
                {
                    msg = "Working";
                    if (PUB.flag.get(eVarBool.FG_PRC_VISIONL) && PUB.flag.get(eVarBool.FG_END_VISIONL) == false)
                        msg += "(LEFT-QR validation)";
                    if (PUB.flag.get(eVarBool.FG_PRC_VISIONR) && PUB.flag.get(eVarBool.FG_END_VISIONR) == false)
                        msg += "(RIGHT-QR validation)";

                    //Conveyor interlock check in conveyor usage mode
                    if (VAR.BOOL[eVarBool.Use_Conveyor])
                    {
                        if (DIO.GetIOInput(eDIName.R_CONV1)  || DIO.GetIOInput(eDIName.R_CONV4))
                        {
                            if (PUB.iLockCVR.IsEmpty() == false)
                                msg += "(Waiting for right conveyor interlock release)";
                        }
                        if (DIO.GetIOInput(eDIName.L_CONV1) || DIO.GetIOInput(eDIName.L_CONV4))
                        {
                            if (PUB.iLockCVL.IsEmpty() == false)
                                msg += "(Waiting for left conveyor interlock release)";
                        }
                    }

                    cur = VAR.TIME.RUN((int)eVarTime.LIVEVIEW1).TotalSeconds;
                    max = AR.SETTING.Data.Timeout_VisionProcessL / 1000.0;
                }
                //else if (PUB.flag.get(eVarBool.RDY_ZL_PICKON))
                //{
                //    var ts = DateTime.Now - Pub.GetVarTime(eVarTime.JOB_END);
                //    msg = string.Format("UNLOADER PICK ON #{0}", PUB.sm.seq.Get(step));
                //    cur = Pub.getRunSteptime(0).TotalSeconds;//ts.TotalSeconds;
                //    max = 10;//COMM.SETTING.Data.Timeout_JOBEnd;
                //}
                //else if (PUB.mot.IsMotion((int)eAxis.Y_PICKER])
                //{
                //    msg = string.Format("Moving");
                //    cur = 0;// Pub.getRunSteptime(0).TotalSeconds;// ts.TotalSeconds;
                //    max = 10;//COMM.SETTING.Data.Timeout_JOBEnd;
                //}
                SetStatusProgress(cur, msg, max, fColor, Color.FromArgb(50, 50, 50));
            }
            else if (PUB.flag.get(eVarBool.FG_MOVE_PICKER))
            {
                SetStatusMessage("X-axis can be moved with buttons", Color.Black, Color.White);
            }
            else
            {
                SetStatusMessage("[" + PUB.sm.Step.ToString() + "]", Color.Red, Color.White);
            }
        }
    }
}
