using AR;
using Project.Dialog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Windows.Forms;

namespace Project
{
    public partial class Model_Operation : Form
    {

        public string Value = string.Empty;
        public Model_Operation()
        {
            InitializeComponent();
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Escape) this.Close(); };
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormClosed += __Closed;
            this.FormClosing += FModelV_FormClosing;
            this.dv.CellContentClick += dv_CellContentClick;
            //if (COMM.SETTING.Data.FullScreen) this.WindowState = FormWindowState.Maximized;
            //this.WindowState = FormWindowState.Normal;
            dvc_bsave.HeaderText = $"BLoad\n(1~8)";
            this.panel3.Visible = PUB.UserAdmin;
        }

        private void FModelV_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Pub.sm.setNewStep(StateMachine.eSystemStep.IDLE);
            if (hasChanged())
            {
                var dlg = UTIL.MsgQ("There are unsaved changes.\n" +
                   "If you proceed, the changed data will be lost\n" +
                   "Do you want to proceed?");

                if (dlg != DialogResult.Yes)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void __Closed(object sender, FormClosedEventArgs e)
        {

            this.ds1.OPModel.TableNewRow -= Model_TableNewRow;
        }

        private void __Load(object sender, EventArgs e)
        {
            this.ds1.Clear();
            this.ds1.OPModel.Merge(PUB.mdm.dataSet.OPModel);
            this.ds1.OPModel.TableNewRow += Model_TableNewRow;
            this.tmDisplay.Start();

            //var MotList = PUB.mdm.dataSet.MCModel.GroupBy(t => t.Title).Select(t => t.Key).ToList();
            //comboBox1.Items.AddRange(MotList.ToArray());

            if (this.ds1.OPModel.Rows.Count < 1)
            {
                var newdr = this.ds1.OPModel.NewOPModelRow();
                newdr.Title = "New Model";
                this.ds1.OPModel.AddOPModelRow(newdr);
                UTIL.MsgI("New model information has been added.\n\nThis is the initial setup, so please check each status value.");
            }

            //dispal current
            if (PUB.Result.isSetvModel)
            {
                arLabel18.Text = PUB.Result.vModel.Title;
                //find data
                var datas = this.ds1.OPModel.Select("", this.bs.Sort);
                for (int i = 0; i < datas.Length; i++)
                {
                    if (datas[i]["Title"].ToString() == PUB.Result.vModel.Title)
                    {
                        this.bs.Position = i;
                        break;
                    }
                }
            }
            else arLabel18.Text = "--";
            //chekauth(false);

            //checkBox1.Enabled = checkBox4.Checked;
            //checkBox2.Enabled = checkBox4.Checked;
            //checkBox3.Enabled = checkBox4.Checked;

            if (PUB.UserAdmin == false)
            {
                //오퍼레이터는 다 못한다
                dv.EditMode = DataGridViewEditMode.EditProgrammatically;
                this.btAdd.Visible = false;
                this.btSave.Visible = false;
                this.btCopy.Visible = false;
                this.toolStripSeparator1.Visible = false;
                this.btDel.Visible = false;
            }

            if (PUB.sm.Step != eSMStep.IDLE)
            {
                btDel.Enabled = false;
                //btCopy.Enabled = false;
                toolStripButton10.Visible = false;
                //Util.MsgE("삭제/복사 작업은 대기 상태일때 가능 합니다");
            }

            //assig check events
            foreach (var c in tabPage1.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Click += Chk_Option_Check;
            }
            foreach (var c in grpApplyWMSinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Click += Chk_WMSinfo_Check;
            }
            foreach (var c in grpApplySidinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Click += Chk_Sidinfo_Check;
            }
            foreach (var c in grpapplyjob.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Click += Chk_JobInfo_Check;
            }
            foreach (var c in GrpSidConvData.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                chk.Click += Chk_SIDConvData_Check;
            }
        }

        private void Chk_Option_Check(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var chk = sender as CheckBox;
            dr.vOption = UTIL.SetBitState(dr.vOption, int.Parse(chk.Tag.ToString()), chk.Checked);
            dr.EndEdit();

            bs_CurrentChanged_1(null, null);
        }
        private void Chk_WMSinfo_Check(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var chk = sender as CheckBox;
            dr.vWMSInfo = UTIL.SetBitState(dr.vWMSInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
            dr.EndEdit();

            bs_CurrentChanged_1(null, null);
        }
        private void Chk_Sidinfo_Check(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var chk = sender as CheckBox;
            dr.vSIDInfo = UTIL.SetBitState(dr.vSIDInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
            dr.EndEdit();

            bs_CurrentChanged_1(null, null);
        }
        private void Chk_JobInfo_Check(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var chk = sender as CheckBox;
            dr.vJobInfo = UTIL.SetBitState(dr.vJobInfo, int.Parse(chk.Tag.ToString()), chk.Checked);
            dr.EndEdit();

            bs_CurrentChanged_1(null, null);
        }
        private void Chk_SIDConvData_Check(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var chk = sender as CheckBox;
            dr.vSIDConv = UTIL.SetBitState(dr.vSIDConv, int.Parse(chk.Tag.ToString()), chk.Checked);
            dr.EndEdit();

            bs_CurrentChanged_1(null, null);
        }
        #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

        void EntertoTab(Control ctl)
        {
            if (ctl.HasChildren)
            {
                foreach (var item in ctl.Controls)
                {
                    if (item.GetType() == typeof(TextBox))
                    {
                        var tb = item as TextBox;
                        tb.KeyDown += (s1, e1) =>
                        {
                            if (e1.KeyCode == Keys.Enter) SendKeys.Send("{TAB}");
                        };
                    }
                }
            }
        }

        void Model_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {

            e.Row["Title"] = DateTime.Now.ToString("yyMMddHHmmss");
            e.Row["BCD_1D"] = true;
            e.Row["BCD_QR"] = false;
            e.Row["BCD_DM"] = true;
            //e.Row["guid"] = Guid.NewGuid().ToString();
            //e.Row["MotionModel"] = "Default";
            //  e.Row["RowCount"] = 5;
            //  e.Row["ColCount"] = 0;
            //   e.Row["Light"] = 50;
        }


        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.MCModelRow;
        }

        private void tmDisplay_Tick(object sender, EventArgs e)
        {
            if (VAR.BOOL[eVarBool.Use_Conveyor])
            {
                btConvOk.BackColor = Color.Lime;
                btConvOff.BackColor = Color.White;
            }
            else
            {
                btConvOk.BackColor = Color.White;
                btConvOff.BackColor = Color.Lime;
            }

        }


        private void dv_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

     
        Boolean hasChanged()
        {
            this.Validate();
            this.bs.EndEdit();
            var chg = this.ds1.OPModel.GetChanges();
            if (chg == null || chg.Rows.Count < 1) return false;
            return true;
        }
        void selectModel()
        {
            //select
            this.Invalidate();
            this.bs.EndEdit();
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            if (dr.Title == "") return;
            this.Value = dr.Title;
            SETTING.User.useConv = VAR.BOOL[eVarBool.Use_Conveyor];
            SETTING.User.Save();
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            //iocontrol
            var f = new Dialog.Quick_Control();
            f.TopMost = true;
            f.Opacity = 0.95;
            f.Show();
        }

 

        void dv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dv.Columns[e.ColumnIndex].DataPropertyName.ToLower() == "spn")
            {
               
            }
        }
       
        private void tbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            var tb = sender as TextBox;
            var str = tb.Text.Trim();
            if (str.isEmpty()) str = "0";
            var c = Color.FromArgb(int.Parse(str));
            if (str.Equals("0") == false) tb.BackColor = c;
            else tb.BackColor = Color.Black;
        }

       

        private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dlg = UTIL.MsgQ("Do you want to delete the currently selected data?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            bs.RemoveCurrent();
            //this.ds1.Model.AcceptChanges();
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;

            //button - save
            this.Validate();
            this.bs.EndEdit();

            if (hasChanged() == true)
            {
                UTIL.MsgE("Need save");
                return;
            }

            if (PUB.PasswordCheck() == false)
            {
                UTIL.MsgE("Password incorrect");
                return;
            }

            var dr = drv.Row as DataSet1.OPModelRow;
            var oldname = dr.Title;
            var newname = UTIL.InputBox("input new name", dr.Title);

            if (newname.Item1 == false) return;
            
            if(dr.Title.Equals(newname.Item2))
            {
                UTIL.MsgE("Same Data");
                return;
            }
                


            
            var dlg = UTIL.MsgQ(string.Format("Do you want to copy the following model information?\n\nNew Model Name : {0}", newname.Item2));
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            var newdr = this.ds1.OPModel.NewOPModelRow();
            UTIL.CopyData(dr, newdr);
            newdr.Title = newname.Item2;
            newdr.idx = this.ds1.OPModel.OrderByDescending(t => t.idx).FirstOrDefault().idx + 1;
            newdr.EndEdit();
            this.ds1.OPModel.AddOPModelRow(newdr);
            if (this.bs.Count > 0) this.bs.Position = this.bs.Count - 1;

            PUB.mdm.dataSet.OPModel.Clear();
            PUB.mdm.dataSet.OPModel.Merge(this.ds1.OPModel);
            PUB.mdm.dataSet.AcceptChanges();
            PUB.mdm.SaveModelV();

            //copy regex
            var cnt = DB.CopyRegEx(oldname,newname.Item2);
            PUB.log.AddAT($"model copy(regex : {cnt})");
        }


        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var f = new AR.Dialog.fTouchKeyFull("Please enter model name", DateTime.Now.ToString("yyyyMMddHHmmss"));
            if (f.ShowDialog() == DialogResult.OK)
            {
                var newdr = this.ds1.OPModel.NewOPModelRow();
                newdr.Title = f.tbInput.Text.Trim();
                newdr.Motion = "Default";
                this.ds1.OPModel.AddOPModelRow(newdr);
                if (this.bs.Count > 0) this.bs.Position = this.bs.Count - 1;
            }
        }

        private void bs_CurrentChanged_1(object sender, EventArgs e)
        {
            //값이바뀌면 허용 바코드 목록을 업데이트 해준다.
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;

            if (dr.IsbOwnZPLNull())
            {
                dr.bOwnZPL = false;
                dr.EndEdit();
            }

            //this.tabControl1.Visible = !dr.Title.StartsWith("101");
            //this.panel6.Visible = !dr.Title.StartsWith("101");
            // this.panel7.Visible = !dr.Title.StartsWith("101");

            //update checkbox
            foreach (var c in tabPage1.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                var val = UTIL.GetBitState(dr.vOption, int.Parse(chk.Tag.ToString()));
                if (chk.Checked != val) chk.Checked = val;
            }
            foreach (var c in grpApplyWMSinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                var val = UTIL.GetBitState(dr.vWMSInfo, int.Parse(chk.Tag.ToString()));
                if (chk.Checked != val) chk.Checked = val;
            }
            foreach (var c in grpApplySidinfo.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                var val = UTIL.GetBitState(dr.vSIDInfo, int.Parse(chk.Tag.ToString()));
                if (chk.Checked != val) chk.Checked = val;
            }
            foreach (var c in grpapplyjob.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                var val = UTIL.GetBitState(dr.vJobInfo, int.Parse(chk.Tag.ToString()));
                if (chk.Checked != val) chk.Checked = val;
            }
            foreach (var c in GrpSidConvData.Controls)
            {
                if (c.GetType() != typeof(CheckBox)) continue;
                var chk = c as CheckBox;
                if (chk.Tag == null) continue;
                var val = UTIL.GetBitState(dr.vSIDConv, int.Parse(chk.Tag.ToString()));
                if (chk.Checked != val) chk.Checked = val;
            }

        }


        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            //button - save
            this.Validate();
            this.bs.EndEdit();

            if (hasChanged() == false)
            {
                PUB.log.Add("Model save: No changes to save");
                return;
            }

            if (PUB.PasswordCheck() == false)
            {
                UTIL.MsgE("Password incorrect");
                return;
            }


            //z position 영역을 문자로 변환한다.
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            dr.EndEdit();
            this.ds1.AcceptChanges();


            PUB.mdm.dataSet.OPModel.Clear();
            PUB.mdm.dataSet.OPModel.Merge(this.ds1.OPModel);
            PUB.mdm.dataSet.AcceptChanges();
            PUB.mdm.SaveModelV();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            if (PUB.sm.Step == eSMStep.RUN || PUB.sm.Step == eSMStep.WAITSTART || PUB.sm.Step == eSMStep.PAUSE)
            {
                UTIL.MsgE("Cannot change model while system is currently running (waiting)");
                return;
            }

            if (hasChanged())
            {
                var dlg = UTIL.MsgQ("There are unsaved changes.\n" +
                    "If you proceed, the changed data will be lost\n" +
                    "Do you want to proceed?");
                if (dlg != DialogResult.Yes) return;
            }
            selectModel();
        }

        private void chkApplySidInfo_CheckStateChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckBox;
            chk.ForeColor = chk.Checked ? Color.Blue : Color.Gray;

            if (chk.Name.Equals(chkApplyJobInfo.Name))
            {
                grpapplyjob.Enabled = chk.Checked;
            }
            if (chk.Name.Equals(chkApplyWMSInfo.Name))
            {
                grpApplyWMSinfo.Enabled = chk.Checked;
            }
            if (chk.Name.Equals(chkApplySidInfo.Name))
            {
                grpApplySidinfo.Enabled = chk.Checked;
            }
            if (chk.Name.Equals(chkApplySIDConvData.Name))
            {
                GrpSidConvData.Enabled = chk.Checked;
            }
         
        }

        private void btConvOk_Click(object sender, EventArgs e)
        {
            VAR.BOOL[eVarBool.Use_Conveyor] = true;
        }

        private void btConvOff_Click(object sender, EventArgs e)
        {
            VAR.BOOL[eVarBool.Use_Conveyor] = false;
        }

        private void tbBypassSID_TextChanged(object sender, EventArgs e)
        {
            var tb = sender as TextBox;
            tb.BackColor = tb.TextLength > 0 ? Color.Gold : Color.WhiteSmoke;
        }

        private void checkBox32_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            var drv = bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;

            if (chkOwnZPL.Checked == false)
            {
                UTIL.MsgE("Individual print code is disabled, so it will not be applied");
            }

            var idx = dr.idx;
            var fn = UTIL.MakePath("Model", idx.ToString(), "zpl.txt");
            var fnBase = UTIL.MakePath("Data","zpl.txt");
            if (System.IO.File.Exists(fnBase) && System.IO.File.Exists(fn) == false)
            {
                UTIL.MsgI("Dedicated output file (ZPL.TXT) does not exist, copying from default");
                var fi = new System.IO.FileInfo(fn);
                if (fi.Directory.Exists == false) fi.Directory.Create();
                System.IO.File.Copy(fnBase, fn, true);
            }
            using (var f = new fZPLEditor(fn))
            {
                f.ShowDialog();
            }
        }

        private void btReName_Click(object sender, EventArgs e)
        {
            //button - save
            this.Validate();
            this.bs.EndEdit();

            if (hasChanged() == true)
            {
                UTIL.MsgE("Need save");
                return;
            }

            if (PUB.PasswordCheck() == false)
            {
                UTIL.MsgE("Password incorrect");
                return;
            }

            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.OPModelRow;
            var beforename = dr.Title;
            var dlg = UTIL.InputBox("Change Model ?Name", dr.Title);
            if (dlg.Item1 == false) return;
            if(beforename.Equals(dlg.Item2))
            {
                UTIL.MsgE("Same data");
                return;
            }
            if (UTIL.MsgQ($"Change model name\nBefore:{beforename},After:{dlg.Item2}") != DialogResult.Yes)
                return;

            dr.Title = dlg.Item2;
            dr.EndEdit();

            //update regexname
            DB.ChangeRegExName(beforename, dlg.Item2);

            PUB.mdm.dataSet.OPModel.Clear();
            PUB.mdm.dataSet.OPModel.Merge(this.ds1.OPModel);
            PUB.mdm.dataSet.AcceptChanges();
            PUB.mdm.SaveModelV();

        }
    }
}

