using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Project
{
    public partial class fModelV : Form
    {

        public string Value = string.Empty;
        public fModelV()
        {
            InitializeComponent();
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => { if (e1.KeyCode == Keys.Escape) this.Close(); };
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormClosed += __Closed;
            this.dv.CellContentClick += dv_CellContentClick;
            
            this.lbTitle.MouseMove += LbTitle_MouseMove;
            this.lbTitle.MouseUp += LbTitle_MouseUp;
            this.lbTitle.MouseDown += LbTitle_MouseDown;
            this.lbTitle.DoubleClick += LbTitle_DoubleClick;
        }

        private void __Closed(object sender, FormClosedEventArgs e)
        {
            //Pub.sm.setNewStep(StateMachine.eSystemStep.IDLE);
            this.ds1.Model.TableNewRow -= Model_TableNewRow;
        }

        private void __Load(object sender, EventArgs e)
        {
            

            this.ds1.Clear();
            this.ds1.Model.Merge(Pub.mdm.dataSet.Model);
            this.ds1.Model.TableNewRow += Model_TableNewRow;
            this.tmDisplay.Start();

            if (this.ds1.Model.Rows.Count < 1)
            {
                var newdr = this.ds1.Model.NewModelRow();
                newdr.Title = "New Model";
                this.ds1.Model.AddModelRow(newdr);
                Util.MsgI("신규 모델 정보가 추가되었습니다.\n\n최초 설정 이므로 각 상태값을 확인 하세요.");
            }
         
            //dispal current
            if (Pub.Result.isSetvModel)
            {
                arLabel18.Text = Pub.Result.vModel.Title;
                //find data
                var datas = this.ds1.Model.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 = "--";

        }
        #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["RowCount"] = 5;
          //  e.Row["ColCount"] = 0;
         //   e.Row["Light"] = 50;
        }

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

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

            Dialog.fPassword f = new Dialog.fPassword();
            if (f.ShowDialog() != DialogResult.OK) return;
            if (f.tbInput.Text != Pub.setting.Password_Setup)
            {
                Util.MsgE("Password incorrect");
                return;
            }

            Pub.mdm.dataSet.Model.Clear();
            Pub.mdm.dataSet.Model.Merge(this.ds1.Model);
            Pub.mdm.dataSet.AcceptChanges();
            Pub.mdm.SaveModelV();
        }

        private void bs_CurrentChanged(object sender, EventArgs e)
        {
            //z range 을 표시한다.

            //z position 영역을 문자로 변환한다.
            //this.list
            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)
        {

        }


        private void dv_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            selectModel();
        }
        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.ModelRow;
            if (dr.Title == "") return;
            this.Value = dr.Title;
            DialogResult = System.Windows.Forms.DialogResult.OK;
        }


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

        private void bindingNavigatorDeleteItem_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dlg = Util.MsgQ("현재 선택된 자료를 삭제하시겠습니까?");
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;
            bs.RemoveCurrent();
            this.ds1.Model.AcceptChanges();
        }

      

        private void tbFind_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                findModel();
            }
        }

        void findModel()
        {
            try
            {
                if (this.tbFind.Text.Trim() == "")
                {
                    this.bs.Filter = "";
                    this.tbFind.BackColor = Color.White;
                }
                else
                {
                    string filter = "title like '%{0}%'";
                    filter = string.Format(filter, tbFind.Text.Trim());
                    this.bs.Filter = filter;
                    this.tbFind.BackColor = Color.SkyBlue;
                    this.tbFind.SelectAll();
                }
            }
            catch (Exception Ex)
            {
                this.bs.Filter = "";
                this.tbFind.BackColor = Color.Tomato;
                Util.MsgE(Ex.Message);
            }
        }
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var f = new Dialog.fTouchKeyFull("INPUT - ", this.tbFind.Text.Trim());
            if (f.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            var inputLot = f.tbInput.Text.Trim().ToUpper();
            //if (inputLot == "") return;
            tbFind.Text = inputLot;
            findModel();
            tbFind.Focus();
            tbFind.SelectAll();
        }

      
        private void button23_Click(object sender, EventArgs e)
        {
            
        }

      

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            var drv = this.bs.Current as DataRowView;
            if (drv == null) return;
            var dr = drv.Row as DataSet1.ModelRow;
            var dlg = Util.MsgQ(string.Format("다음 모델 정보를 복사하시겠습니까?\n\n모델명 : {0}", dr.Title));
            if (dlg != System.Windows.Forms.DialogResult.Yes) return;

            var newdr = this.ds1.Model.NewModelRow();
            Util.CopyData(dr, newdr);
            newdr.Title += "-copy-";
            newdr.idx = this.ds1.Model.OrderByDescending(t => t.idx).FirstOrDefault().idx + 1;
            newdr.EndEdit();
            this.ds1.Model.AddModelRow(newdr);
            if (this.bs.Count > 0) this.bs.Position = this.bs.Count - 1;
        }

        void dv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(this.dv.Columns[e.ColumnIndex].DataPropertyName.ToLower()=="spn")
            {
                //var drv = dv.Rows[e.RowIndex].DataBoundItem as DataRowView;
                //var dr = drv.Row as DataSet1.ModelRow;
                //var spn = dr.SPN;
                //spn = selectSPn(spn);
                //if(spn != "")
                //{
                //    dr.SPN = spn;
                //    dv.EndEdit();
                //}
            }
        }
        //string selectSPn(string selectedname)
        //{
        //    var od = new OpenFileDialog();
        //    od.InitialDirectory = Pub.setting.SPNPath;
        //    od.FileName = selectedname;
        //    if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return "";
        //    var fi = new System.IO.FileInfo(od.FileName);
        //    if (Pub.setting.SPNPath != fi.Directory.FullName)
        //    {
        //        Pub.setting.SPNPath = fi.Directory.FullName;
        //        Pub.setting.Save();
        //    }
        //    var SPN = fi.Name.Replace(fi.Extension, "");
        //    return SPN;
        //}

        private void toolStripButton3_Click(object sender, EventArgs e)
        {


            //if(Pub.setting.SPNPath == "")
            //{
            //    Util.MsgE("SEM 파일 저장 경로가 입력되지 않았습니다\n"+
            //        "환경설정에서 해당 값을 입력할 수 있습니다");
            //    return;
            //}
            //Util.RunExplorer(Pub.setting.SPNPath);
            //return;



            //var drv = this.bs.Current as DataRowView;
            //if (drv == null) return;
            //var dr = drv.Row as DataSet1.ModelRow;

            //var spn = selectSPn(dr.SPN);
            //if(spn != "")
            //{
            //    dr.SPN = spn;
            //    dr.EndEdit();
            //}
        }

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

