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 AR;


namespace Project
{
    public partial class fSetup : Form
    {
        readonly System.Windows.Forms.Timer tmDisplay;
        public fSetup()
        {
            InitializeComponent();
            tmDisplay = new System.Windows.Forms.Timer
            {
                Interval = 200
            };
            tmDisplay.Tick += TmDisplay_Tick;
            this.VisibleChanged += FSetup_VisibleChanged;
            this.FormClosed += FSetup_FormClosed;
            this.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Escape) this.Close(); };

            this.panTopMenu.MouseMove += LbTitle_MouseMove;
            this.panTopMenu.MouseUp += LbTitle_MouseUp;
            this.panTopMenu.MouseDown += LbTitle_MouseDown;
            this.panTopMenu.DoubleClick += LbTitle_DoubleClick;

            this.propertyGrid1.SelectedObject = PUB.setting;
        }

        private void FSetup_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.timer1.Stop();
            this.timer1.Enabled = false;
        }

        private void FSetup_VisibleChanged(object sender, EventArgs e)
        {
            PUB.log.Add("setup screen show : " + this.Visible.ToString());
            if (this.Visible) tmDisplay.Start();
            else tmDisplay.Stop();
        }

        private void fSetup_Load(object sender, EventArgs e)
        {

            //통신값 표시
            tbPortAGV.Text = PUB.setting.Port_AGV;
            tbPortXBE.Text = PUB.setting.Port_XBE;
            tbportBMS.Text = PUB.setting.Port_BAT;

            tbBaudAGV.Text = PUB.setting.Baud_AGV.ToString();
            tbBaudXBE.Text = PUB.setting.Baud_XBE.ToString();
            tbBaudBAT.Text = PUB.setting.Baud_BAT.ToString();

            valIntervalXBE.Value = PUB.setting.interval_xbe;
            vcpidDS.Value = PUB.setting.ZSpeed;
            valIntervalBMS.Value = PUB.setting.interval_bms;
            tbChargerID.Value = PUB.setting.ChargerID;

            vcSCK.Value = PUB.setting.SCK;
            vcSSK.Value = PUB.setting.SSK;
            vcSTT.Value = PUB.setting.STT;
            vcSAD.Value = PUB.setting.SAD;
            vcXBID.Value = PUB.setting.XBE_ID;
            vcGDS.Value = PUB.setting.GDSValue;

            tbagvaddr.Text = PUB.setting.AGV_ADDRESS;
            tbagvpanid.Text = PUB.setting.AGV_PANID;
            tbagvchannel.Text = PUB.setting.AGV_CHANNEL;

            //속도 저/중/고
            vcSpeedL.Value = PUB.setting.SPD_L;
            vcSpeedM.Value = PUB.setting.SPD_M;
            vcSpeedH.Value = PUB.setting.SPD_H;
            vcSpeedDrive.Value = PUB.setting.SPD_DRIVE;

            //속도 정지/회전
            vcSpeedS.Value = PUB.setting.SPD_S;
            vcSpeedR.Value = PUB.setting.SPD_R;

            //PID-P
            vcpidPH.Value = PUB.setting.PID_PH;
            vcpidPM.Value = PUB.setting.PID_PM;
            vcpidPL.Value = PUB.setting.PID_PL;

            //PID-I
            vcpidIH.Value = PUB.setting.PID_IH;
            vcpidIM.Value = PUB.setting.PID_IM;
            vcpidIL.Value = PUB.setting.PID_IL;

            //PID-D
            vcpidDH.Value = PUB.setting.PID_DH;
            vcpidDM.Value = PUB.setting.PID_DM;
            vcpidDL.Value = PUB.setting.PID_DL;

            //정지상수
            vcpidPS.Value = PUB.setting.PID_PS;
            vcpidIS.Value = PUB.setting.PID_IS;
            vcpidDS.Value = PUB.setting.PID_DS;

            SetColorValue(btSpeaker, PUB.setting.Enable_Speak);
            SetColorValue(btAutoCharge, PUB.setting.Enable_AutoCharge);
            SetColorValue(btMusic, PUB.setting.Enable_Music);
            nudDoorSoundTerm.Value = PUB.setting.alarmSoundTerm;
            chkClear1.Checked = PUB.setting.datetime_Check_1;
            chkClear2.Checked = PUB.setting.datetime_Check_2;
            cleartime1.Value = DateTime.Parse("1982-11-23 " + PUB.setting.datetime_Reset_1 + ":00");
            cleartime2.Value = DateTime.Parse("1982-11-23 " + PUB.setting.datetime_Reset_2 + ":00");
            chkClearPos.Checked = PUB.setting.AutoModeOffAndClearPosition;

            //PLC옵션
            nudMusicVol.Value = PUB.setting.musicvol;// (int)(PUB.mplayer.Volume * 100.0);
            tbMusic.Text = PUB.setting.musicfile;
            this.chkFullScreen.Checked = PUB.setting.FullScreen;
            this.chkDetectManualCharge.Checked = PUB.setting.DetectManualCharge;

            //충전
            // chkAutoCharge.Checked = PUB.setting.Enable_AutoCharge;
            vcChargeStartLevel.Value = PUB.setting.ChargeStartLevel;
            vcChargeMaxLevel.Value = PUB.setting.ChargeMaxLevel;
            vcChargeMaxTime.Value = PUB.setting.ChargeMaxTime;
            vcChargeRetryTerm.Value = PUB.setting.ChargeRetryTerm;
            vcChargeSearchTime.Value = PUB.setting.ChargeSearchTime;
            vcChargeEmergencyLevel.Value = PUB.setting.ChargeEmergencyLevel;
            vcChargeWaitSec.Value = PUB.setting.ChargetWaitSec;
            tbMCID.Text = PUB.setting.MCID;

            timer1.Start();
        }


        #region "Mouse Form Move"

        private Boolean fMove = false;
        private Point MDownPos;

        private void LbTitle_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized) this.WindowState = FormWindowState.Normal;
            else this.WindowState = FormWindowState.Maximized;
        }
        private void LbTitle_MouseMove(object sender, MouseEventArgs e)
        {
            if (fMove)
            {
                Point offset = new Point(e.X - MDownPos.X, e.Y - MDownPos.Y);
                this.Left += offset.X;
                this.Top += offset.Y;
                //offset = new Point(0, 0);
            }
        }
        private void LbTitle_MouseUp(object sender, MouseEventArgs e)
        {
            fMove = false;
        }
        private void LbTitle_MouseDown(object sender, MouseEventArgs e)
        {
            MDownPos = new Point(e.X, e.Y);
            fMove = true;
        }

        #endregion


        private void btSave_Click(object sender, EventArgs e)
        {
            if (PUB.CheckPassword() == false)
            {
                UTIL.MsgE("암호가 일치하지 않습니다");
                return;
            }

            this.Validate();
            propertyGrid1.Invalidate();

            //통신정보저장
            PUB.setting.Port_XBE = tbPortXBE.Text;
            PUB.setting.Port_AGV = tbPortAGV.Text;
            PUB.setting.Port_BAT = tbportBMS.Text;

            PUB.setting.Baud_XBE = int.Parse(tbBaudXBE.Text);
            PUB.setting.Baud_AGV = int.Parse(tbBaudAGV.Text);
            PUB.setting.Baud_BAT = int.Parse(tbBaudBAT.Text);
            PUB.setting.ChargerID = (int)(tbChargerID.Value);

            PUB.setting.interval_bms = (int)valIntervalBMS.Value;
            PUB.setting.interval_xbe = (float)valIntervalXBE.Value;
            PUB.setting.ZSpeed = (byte)vcpidDS.Value;
            PUB.setting.AutoModeOffAndClearPosition = this.chkClearPos.Checked;

            //AGV정보 저장
            PUB.setting.Enable_Speak = this.btSpeaker.ProgressValue != 0;
            PUB.setting.Enable_Music = this.btMusic.ProgressValue != 0;
            PUB.setting.Enable_AutoCharge = this.btAutoCharge.ProgressValue != 0;

            //충전
            PUB.setting.ChargeStartLevel = (int)vcChargeStartLevel.Value;
            PUB.setting.ChargeMaxLevel = (int)vcChargeMaxLevel.Value;
            PUB.setting.ChargeMaxTime = (int)vcChargeMaxTime.Value;
            PUB.setting.ChargeRetryTerm = (int)vcChargeRetryTerm.Value;
            PUB.setting.ChargeSearchTime = (int)vcChargeSearchTime.Value;
            PUB.setting.ChargeEmergencyLevel = (int)vcChargeEmergencyLevel.Value;
            PUB.setting.ChargetWaitSec = (int)vcChargeWaitSec.Value;

            PUB.setting.SCK = (int)vcSCK.Value;
            PUB.setting.SSK = (int)vcSSK.Value;
            PUB.setting.STT = (int)vcSTT.Value;
            PUB.setting.SAD = (int)vcSAD.Value;
            PUB.setting.XBE_ID = (byte)vcXBID.Value;
            PUB.setting.GDSValue = (UInt16)vcGDS.Value;

            //속도 저/중/고
            PUB.setting.SPD_L = (int)vcSpeedL.Value;
            PUB.setting.SPD_M = (int)vcSpeedM.Value;
            PUB.setting.SPD_H = (int)vcSpeedH.Value;
            PUB.setting.SPD_DRIVE = (int)vcSpeedDrive.Value;

            //속도 정지/회전      
            PUB.setting.SPD_S = (int)vcSpeedS.Value;
            PUB.setting.SPD_R = (int)vcSpeedR.Value;

            //PID-P
            PUB.setting.PID_PH = (int)vcpidPH.Value;
            PUB.setting.PID_PM = (int)vcpidPM.Value;
            PUB.setting.PID_PL = (int)vcpidPL.Value;

            //PID-I                          ;
            PUB.setting.PID_IH = (int)vcpidIH.Value;
            PUB.setting.PID_IM = (int)vcpidIM.Value;
            PUB.setting.PID_IL = (int)vcpidIL.Value;

            //PID-D                          ;
            PUB.setting.PID_DH = (int)vcpidDH.Value;
            PUB.setting.PID_DM = (int)vcpidDM.Value;
            PUB.setting.PID_DL = (int)vcpidDL.Value;

            //정지상수                        ;
            PUB.setting.PID_PS = (int)vcpidPS.Value;
            PUB.setting.PID_IS = (int)vcpidIS.Value;
            PUB.setting.PID_DS = (int)vcpidDS.Value;

            //시스템옵션
            PUB.setting.ChargeMaxTime = (int)vcChargeMaxTime.Value;
            PUB.setting.ChargeRetryTerm = (int)vcChargeRetryTerm.Value;

            //초기화시간
            PUB.setting.datetime_Check_1 = chkClear1.Checked;
            PUB.setting.datetime_Check_2 = chkClear2.Checked;
            PUB.setting.datetime_Reset_1 = cleartime1.Value.ToString("HH:mm");
            PUB.setting.datetime_Reset_2 = cleartime2.Value.ToString("HH:mm");

            //PLC옵션
            //PUB.setting.musicvol = (int)nudMusicVol.Value;
            PUB.SetVolume((int)nudMusicVol.Value);
            PUB.setting.ChargeSearchTime = (int)vcChargeSearchTime.Value;

            PUB.setting.alarmSoundTerm = (int)nudDoorSoundTerm.Value;
            if (PUB.setting.alarmSoundTerm < 1) PUB.setting.alarmSoundTerm = 15; //기본값 15초

            PUB.setting.musicfile = tbMusic.Text.Trim();
            PUB.setting.FullScreen = this.chkFullScreen.Checked;
            PUB.setting.ChargeEmergencyLevel = (int)this.vcChargeEmergencyLevel.Value;
            PUB.setting.ChargeStartLevel = (int)this.vcChargeStartLevel.Value;
            PUB.setting.ChargeMaxLevel = (int)this.vcChargeMaxLevel.Value;

            PUB.setting.DetectManualCharge = this.chkDetectManualCharge.Checked;
            PUB.setting.MCID = tbMCID.Text.Trim();

            PUB.setting.Save();

            PUB.log.AddAT("환경설정:저장완료");


            //plc에 정보를 전송하고 그 값의 회신을 체크한다
            DialogResult = DialogResult.OK;
        }

        void SetColorValue(arCtl.arLabel ctl, Boolean value)
        {
            if (value)
            {
                ctl.BackColor = Color.Green;
                ctl.BackColor2 = Color.Lime;
                ctl.ProgressValue = 1;
            }
            else
            {
                ctl.BackColor = Color.FromArgb(50, 50, 50);
                ctl.BackColor2 = Color.Gray;
                ctl.ProgressValue = 0;
            }
        }

        private void TmDisplay_Tick(object sender, EventArgs e)
        {
            //Pub.log.Add("timer run");
        }

        private void vcChargeLow_ButtonClick(object sender, AGVControl.ValueSelect.ButtonClickEventArgs e)
        {
            //버튼이클릭되엇다 각 버튼은 tag값으로 처히
            var button = sender as AGVControl.ValueSelect;
            var tagStr = button.Tag.ToString();
            PUB.log.Add("Setup:Click:" + tagStr + ":" + e.Button.ToString());
            if (e.Button == MouseButtons.Middle)
            {
                //중앙부 숫자를 클릭했다
                var f = AR.UTIL.InputBox("input", button.Value.ToString());// new Dialog.fInput(button.Value.ToString());
                if (f.Item1)
                {
                    Console.WriteLine("value change : " + f.Item2);// ;
                    button.Value = double.Parse(f.Item2);
                }
            }
        }


        private void vcChargeLow_ValueChanged(object sender, EventArgs e)
        {
            //버튼이클릭되엇다 각 버튼은 tag값으로 처히
            var button = sender as AGVControl.ValueSelect;
            var tagStr = button.Tag.ToString();
            PUB.log.Add("Setup:ValueChange:" + tagStr + ":" + button.Name);

            //if (tagStr == "SH" && PUB.setting.WheelSpeedHigh != button.Value)
            //    button.BackColor = Color.Tomato;
            //else if (tagStr == "SL" && PUB.setting.WheelSpeedLow != button.Value)
            //    button.BackColor = Color.Tomato;
            //else if (tagStr == "SC" && PUB.setting.WheelSpeedCharge != button.Value)
            //    button.BackColor = Color.Tomato;
            ////else if (tagStr == "MT" && Pub.setting.MoveThreshold != button.Value)
            ////    button.BackColor = Color.Tomato;
            //else if (tagStr == "ST" && PUB.setting.MarkSensorThreshold != button.Value)
            //    button.BackColor = Color.Tomato;
            //else if (tagStr == "BL" && PUB.setting.BalanceThreshold != button.Value)
            //    button.BackColor = Color.Tomato;
            //else if (tagStr == "BU" && PUB.setting.BalanceThresholdUp != button.Value)
            //    button.BackColor = Color.Tomato;
            //else button.BackColor = Color.Navy;

        }

        private void btMagnet_Click(object sender, EventArgs e)
        {
            //버튼이클릭되엇다 각 버튼은 tag값으로 처히
            var button = sender as arCtl.arLabel;

            var tagStr = button.Tag.ToString();
            PUB.log.Add("Setup:ButtonClick:" + tagStr + ":" + button.Name);

            if (button.ProgressValue == 0)
            {
                //메세지로 사용여부를 확인한다.
                var msg = "다음 기능을 사용하시겠습니까?\n";
                if (tagStr == "0") msg += "[음성지원]\n" +
                        " * 동작 상태를 음성으로 지원 합니다";
                else if (tagStr == "1") msg += "[자동충전]\n" +
                        " * 자동으로 충전을 진행 합니다\n" +
                        " * [충전] 탭에서 설정값을 확인할 수 있습니다";
                else if (tagStr == "2") msg += "[배경음악]\n" +
                         " * 이동시 음악을 플레이 합니다";
                var dlg = UTIL.MsgQ(msg);
                if (dlg == DialogResult.Yes)
                {
                    SetColorValue(button, true);
                }
            }
            else SetColorValue(button, false);
        }

        private void btSelXbee_Click(object sender, EventArgs e)
        {
            //포트를 선택한 후 표시해준다.
            var but = sender as Button;
            var tagStr = but.Tag.ToString();
            var newPort = PUB.SelectSerialPort();
            if (newPort.isEmpty()) return;

            if (tagStr == "XBE") tbPortXBE.Text = newPort;
            else if (tagStr == "AGV") tbPortAGV.Text = newPort;
            //  else if (tagStr == "PLC") tbPortPLC.Text = newPort;
            else if (tagStr == "BAT") tbportBMS.Text = newPort;

        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var od = new OpenFileDialog())
            {
                if (tbMusic.Text.isEmpty() == false)
                {
                    var fi = new System.IO.FileInfo(tbMusic.Text);
                    od.FileName = fi.Name;
                    od.InitialDirectory = fi.Directory.FullName;
                }

                if (od.ShowDialog() == DialogResult.OK)
                {
                    tbMusic.Text = od.FileName;
                }
            }


        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (System.IO.File.Exists(tbMusic.Text) == false)
            {
                UTIL.MsgE("파일이 없습니다");
                return;
            }
            try
            {
                if (PUB.mplayer.SoundLocation.isEmpty() == false) PUB.mplayer.Stop();
                PUB.mplayer.SoundLocation = tbMusic.Text;// (new Uri(tbMusic.Text));
                PUB.mplayer.Play();
                PUB.bPlayMusic = true;
            }
            catch (Exception ex)
            {
                UTIL.MsgE("music open error\n\n" + ex.Message);
            }

        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            PUB.mplayer.Stop();
            PUB.bPlayMusic = false;
        }


        private void button3_Click(object sender, EventArgs e)
        {
            if (this.tbPortAGV.Text == "COM21")
            {
                this.tbPortAGV.Text = "COM11";
                //    this.tbPortPLC.Text = "COM6";
                this.tbportBMS.Text = "COM15";
                this.tbPortXBE.Text = "COM18";
            }
            else
            {
                this.tbPortAGV.Text = "COM21";
                //  this.tbPortPLC.Text = "COM31";
                this.tbportBMS.Text = "COM41";
                this.tbPortXBE.Text = "COM51";
            }

        }

        private void valIntervalBMS_ButtonClick(object sender, AGVControl.ValueSelect.ButtonClickEventArgs e)
        {
            //버튼이클릭되엇다 각 버튼은 tag값으로 처히
            var button = sender as AGVControl.ValueSelect;
            var tagStr = button.Tag.ToString();
            PUB.log.Add("Setup:Click:" + tagStr + ":" + e.Button.ToString());
            if (e.Button == MouseButtons.Middle)
            {
                //중앙부 숫자를 클릭했다
                var f = AR.UTIL.InputBox("input", button.Value.ToString());// new Dialog.fInput(button.Value.ToString());
                if (f.Item1)
                {
                    Console.WriteLine("value change : " + f.Item2);
                    button.Value = double.Parse(f.Item2);
                }
            }
        }

        private void arLabel1_Click(object sender, EventArgs e)
        {
            var buts = new arCtl.arLabel[] { bt0, bt1, bt2, bt3, bt5 };
            foreach (var lb in buts)
            {
                lb.BackColor = Color.DimGray;
                lb.BackColor2 = Color.Gray;
            }
            var bt = sender as arCtl.arLabel;
            bt.BackColor = Color.Lime;
            bt.BackColor2 = Color.Green;
            var index = int.Parse(bt.Tag.ToString());
            this.tabControl1.SelectedIndex = index;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            var value = tbagvaddr.Text.PadLeft(4, '0');
            if (PUB.AGV.AGVCommand("SAD", value) == arDev.eNarumiCommandResult.Success)
            {
                PUB.setting.AGV_ADDRESS = value;
                PUB.setting.Save();
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            var value = tbagvpanid.Text.PadLeft(4, '0');
            if (PUB.AGV.AGVCommand("SPN", value) == arDev.eNarumiCommandResult.Success)
            {
                PUB.setting.AGV_PANID = value;
                PUB.setting.Save();
            }

        }

        private void button6_Click(object sender, EventArgs e)
        {
            var value = tbagvchannel.Text.PadLeft(4, '0');
            if (PUB.AGV.AGVCommand("SCH", value) == arDev.eNarumiCommandResult.Success)
            {
                PUB.setting.AGV_CHANNEL = value;
                PUB.setting.Save();
            }


        }

        private void tbagvaddr_Click(object sender, EventArgs e)
        {
            var tb = sender as TextBox;
            var rlt = UTIL.InputBox("input vlaue", tb.Text);
            if (rlt.Item1 == false) return;
            if (rlt.Item2.isEmpty()) return;
            tb.Text = rlt.Item2;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            var value = (ushort)vcGDS.Value;
            var rlt = PUB.AGV.TurnGDSCenterScope(value);
            if (rlt != arDev.eNarumiCommandResult.Success) UTIL.MsgE($"Error\n{rlt}");
            else UTIL.MsgI("OK");
        }
    }
}
