using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using AR;

namespace Project
{
    public partial class FMain
    {
        //Int32[] _hDevice = new Int32[] { 0, 0, 0 };
        //Int32[] _width = new Int32[] { 0, 0, 0 };
        //Int32[] _height = new Int32[] { 0, 0, 0 };
        //Int32[] _stride = new Int32[] { 0, 0, 0 };
        //Int32[] _bufferSize = new Int32[] { 0, 0, 0 };
        //Boolean[] _isCrevisOpen = new bool[] { false, false, false };
        //Boolean[] _isCrevisACQ = new bool[] { false, false, false };
        // IntPtr[] _pImage = new IntPtr[] { IntPtr.Zero, IntPtr.Zero, IntPtr.Zero };

        public void _STEP_INIT_START(eSMStep step)
        {

            int progress = 0;
            var ProgressMax = 13;
            Color fColor = Color.DarkViolet;


            PUB.sm.RaiseStateProgress(++progress, "Motion Initialize", ProgressMax, fColor); System.Threading.Thread.Sleep(5);
            if (PUB.mot.Init() == false)
            {
                PUB.log.AddE(string.Format("MOT INIT ERROR : {0}", PUB.mot.ErrorMessage));
                PUB.log.AddE("Motion initialization error, retrying shortly");
                System.Threading.Thread.Sleep(1000);
                if (PUB.mot.Init() == false)
                {
                    PUB.log.AddE("Motion initialization retry failed " + PUB.mot.ErrorMessage);
                }
            }
            _SM_RUN_INIT_MOTION();


            PUB.sm.RaiseStateProgress(++progress, "DIO Initialize", ProgressMax, fColor); System.Threading.Thread.Sleep(5);
            if (PUB.dio.Init())
            {
                DIO.InitDIOSensitive();
                PUB.log.Add("DIO RUN MONITOR");
                PUB.dio.RunMonitor();


                //포트동작을 멈춘다
                DIO.SetPortMotor(0, eMotDir.CW, false, "init");
                DIO.SetPortMotor(1, eMotDir.CW, false, "init");
                DIO.SetPortMotor(2, eMotDir.CW, false, "init");
            }
            else PUB.log.AddE(string.Format("DIO INIT ERROR : {0}", PUB.dio.ErrorMessage));
            TowerLamp.Init(PUB.dio,
                DIO.Pin[eDOName.TWR_REDF].terminalno,
                DIO.Pin[eDOName.TWR_GRNF].terminalno,
                DIO.Pin[eDOName.TWR_YELF].terminalno);

            TowerLamp.Enable = !SETTING.Data.Disable_TowerLamp;

            PUB.sm.RaiseStateProgress(++progress, "Set DIO Names", ProgressMax, fColor); System.Threading.Thread.Sleep(5);
            _SM_RUN_INIT_SETDIONAME();

            PUB.log.AddI("Motion initialization flag setup complete");
            PUB.flag.set(eVarBool.FG_INIT_MOTIO, true, "INIT");

            //230504
            hmi1.SetDIO(PUB.dio);
            hmi1.SetMOT(PUB.mot);

            //남은 공간
            PUB.sm.RaiseStateProgress(++progress, "Space Check", ProgressMax, fColor); System.Threading.Thread.Sleep(5);
            CheckFreeSpace(); //181225


            //프린터설정
            PUB.sm.RaiseStateProgress(++progress, "Printer Setup", ProgressMax, fColor); System.Threading.Thread.Sleep(5);
            PUB.PrinterL = new Device.SATOPrinterAPI();
            PUB.PrinterL.PortName = AR.SETTING.Data.PrintL_Port;
            PUB.PrinterL.BaudRate = AR.SETTING.Data.PrintL_Baud;

            PUB.PrinterR = new Device.SATOPrinterAPI();
            PUB.PrinterR.PortName = AR.SETTING.Data.PrintR_Port;
            PUB.PrinterR.BaudRate = AR.SETTING.Data.PrintR_Baud;

            PUB.flag.set(eVarBool.FG_INIT_PRINTER, true, "INIT");

            //모델자동선택 181206
            PUB.sm.RaiseStateProgress(++progress, "Previous Model Check", ProgressMax, fColor); System.Threading.Thread.Sleep(5);

            //
            if (SETTING.User.LastModelV != "") PUB.SelectModelV(SETTING.User.LastModelV, false);
            var motionmodel = SETTING.User.LastModelM;
            if (motionmodel.isEmpty()) motionmodel = PUB.Result.vModel.Motion ?? string.Empty;
            if (motionmodel.ToUpper().StartsWith("CONV")) PUB.flag.set(eVarBool.Use_Conveyor, true, "load");
            else PUB.flag.set(eVarBool.Use_Conveyor, false, "load");
            PUB.SelectModelM(motionmodel, false);

            PUB.sm.RaiseStateProgress(ProgressMax, "Initialization Complete", ProgressMax, Color.Gold); System.Threading.Thread.Sleep(5);
            PUB.log.Add("init finish");

            //조명 ON
            DIO.SetRoomLight(true);
        }

        public StepResult _STEP_INIT(eSMStep step, TimeSpan stepTime, TimeSpan seqTime)
        {
            PUB.sm.SetNewStep(eSMStep.IDLE);
            return StepResult.Complete;
        }

        public void _SM_RUN_INIT_SETDIONAME()
        {
            //DIO 이름설정
            Console.WriteLine("## SET DI NAME ##");
            for (int i = 0; i < PUB.dio.GetDICount; i++)
            {
                var name = Enum.GetName(typeof(eDIName), i);
                Console.WriteLine($"[{i}] {name}");
                PUB.dio.SetDIName(i, name);
            }
            Console.WriteLine("## SET DO NAME ##");
            for (int i = 0; i < PUB.dio.GetDOCount; i++)
            {
                var name = Enum.GetName(typeof(eDOName), i);
                Console.WriteLine($"[{i}] {name}");
                PUB.dio.SetDOName(i, name);
            }

            //Console.WriteLine("## SET FLAG NAME ##");
            //for (int i = 0; i < PUB.flag.Length; i++)
            //{
            //    var name = Enum.GetName(typeof(eFlag), i);
            //    PUB.flag.Name[i] = name;
            //    Console.WriteLine($"[{i}] {name}");
            //}
        }

        private void _SM_RUN_INIT_MOTION()
        {
            PUB.mot.SetAlarmClearOn();
            System.Threading.Thread.Sleep(5);
            PUB.mot.SetAlarmClearOff();

            //7개의 축을 사용한다
            if (PUB.mot.IsInit == false)
            {
                PUB.log.AddE("Motion board initialization error, configuration will not proceed");
            }
            else
            {
                for (short i = 0; i < SETTING.System.MotaxisCount; i++)
                {
                    //설정파일이 있다면 불러온다
                    var file = System.IO.Path.Combine(UTIL.CurrentPath, "Model", "axis" + i.ToString() + ".motaxt");
                    if (System.IO.File.Exists(file) == false)
                    {
                        PUB.log.AddAT($"Motion ({i}) configuration file not found!!");
                        PUB.mot.InitAxis(i, file);
                    }
                    else
                    {
                        if (PUB.mot.InitAxis((short)i, file) == false)
                            PUB.log.AddE("Motion setup failed axis:" + i.ToString());
                        else
                            PUB.log.AddI($"Motion ({i}) setup complete");
                    }
                }

                //EStop Disable
                PUB.mot.SetEStopEnable(0, false);
                PUB.mot.SetEStopEnable(1, false);
                PUB.mot.SetEStopEnable(2, false);
                PUB.mot.SetEStopEnable(3, false);
                PUB.mot.SetEStopEnable(4, false);
                PUB.mot.SetEStopEnable(5, false);
                PUB.mot.SetEStopEnable(6, false);

                //softlimit 적용 - 201214
                UpdateSoftLimit();


                PUB.log.Add("MOT RUN MONITOR");
                PUB.mot.RunMonitor();
                PUB.log.AddAT("ALL SERVO ON");
                PUB.mot.SetServOn(true);
            }

        }
    }
}
