using AR;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project.Dialog
{
    public partial class RegExRule : Form
    {
        string bcdteststring = "";
        public RegExRule()
        {
            InitializeComponent();
            this.dv1.BorderStyle = BorderStyle.None;
            this.dataSet1.K4EE_Component_Reel_RegExRule.TableNewRow += (s1, e1) =>
            {
                if (PUB.Result.isSetvModel)
                    e1.Row["CustCode"] = PUB.Result.vModel.Title;
            };
            dataGridViewTextBoxColumn1.Visible = false;

            //모델목록을 업데이트한다.
            cmbModelList.Items.Clear();
            foreach (var dr in PUB.mdm.dataSet.OPModel.OrderBy(t => t.Title))
                cmbModelList.Items.Add(dr.Title);
            cmbModelList.Items.Add("ALL");

            //현재 선택된 모델을 자동선택한다.
            cmbModelList.Text = PUB.Result.vModel.Title;
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) =>
            {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };

            LoadSaveBCDtestData();
        }

        void LoadSaveBCDtestData(bool load = true)
        {
            var fn = "bcdtestlist.txt";
            if (load)
            {
                this.cmbBCDTestBox.Items.Clear();
                if (System.IO.File.Exists(fn))
                {
                    bcdteststring = System.IO.File.ReadAllText(fn, System.Text.Encoding.Default).Replace("\r", "");
                    var lines = bcdteststring.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var lin in lines)
                    {
                        this.cmbBCDTestBox.Items.Add(lin);
                    }
                }
                else
                {
                    this.cmbBCDTestBox.Items.Add($"101415540;LC15848629;TAIYOYUDEN;20000;RC18091A2526JMN;20250215");
                }
            }
            else
            {
                //save
                var sb = new System.Text.StringBuilder();
                foreach (string item in this.cmbBCDTestBox.Items)
                    sb.AppendLine(item);
                System.IO.File.WriteAllText(fn, sb.ToString(), System.Text.Encoding.Default);
            }

        }

        private void RegExRule_Load(object sender, EventArgs e)
        {
            if (cmbModelList.SelectedIndex == -1 && cmbModelList.Items.Count > 0)
                cmbModelList.SelectedIndex = 0;
        }

        private void component_Reel_RegExRuleBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.bs.EndEdit();
            var cnt1 = this.ta.Update(this.dataSet1.K4EE_Component_Reel_RegExRule);
            //var cnt = this.tam.UpdateAll(this.dataSet1);
            if (cnt1 == 0)
            {
                UTIL.MsgE("No content has been saved");
            }
            else UTIL.MsgI($"{cnt1} records have been saved");
            lock (PUB.Result.BCDPatternLock)
            {
                var modelName = PUB.Result.vModel.Title;
                PUB.Result.BCDPattern = PUB.GetPatterns(modelName, false);
                PUB.Result.BCDIgnorePattern = PUB.GetPatterns(modelName, true);
                PUB.log.Add($"Model pattern loading: {PUB.Result.BCDPattern.Count}/{PUB.Result.BCDIgnorePattern.Count}");
            }

            dv1.AutoResizeColumns();
        }

        private void RefreshList(string cust)
        {
            try
            {

                if (cust == "ALL")
                {
                    dvcModelName.Visible = true;
                    this.ta.FillAll(this.dataSet1.K4EE_Component_Reel_RegExRule);
                }
                else
                {
                    dvcModelName.Visible = false;
                    this.ta.FillByWithSample(this.dataSet1.K4EE_Component_Reel_RegExRule, cust);
                }

                foreach (DataGridViewRow drow in this.dv1.Rows)
                {
                    var drv = drow.DataBoundItem as DataRowView;
                    if (drv == null) continue;
                    var dr = drv.Row as DataSet1.K4EE_Component_Reel_RegExRuleRow;
                    if (dr.IsCustCodeNull() || dr.CustCode.isEmpty())
                        drow.DefaultCellStyle.BackColor = Color.DimGray;
                    else
                        drow.DefaultCellStyle.BackColor = Color.WhiteSmoke;
                }

            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
            dv1.AutoResizeColumns();

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var title = cmbModelList.Text;
            if (title.isEmpty()) title = PUB.Result.vModel.Title;
            RefreshList(title);
        }

        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.K4EE_Component_Reel_RegExRuleRow;
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            try
            {
                DataSet1 ds1 = new DataSet1();
                this.ta.FillAll(ds1.K4EE_Component_Reel_RegExRule);

                var path = UTIL.MakePath("Export", "BarcodeRule.xml");
                var fi = new System.IO.FileInfo(path);
                if (fi.Directory.Exists == false) fi.Directory.Create();
                ds1.K4EE_Component_Reel_RegExRule.WriteXml(path);
                UTIL.MsgI($"Export list File = {path},count={ds1.K4EE_Component_Reel_RegExRule.Count}");
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        private void btBcdTest_Click(object sender, EventArgs e)
        {

            var bcd = cmbBCDTestBox.Text.Trim();


            //없는 문자라면 신규로 테스트한다.
            if (cmbBCDTestBox.Items.Contains(bcd) == false)
                cmbBCDTestBox.Items.Add(bcd);

            //test
            LoadSaveBCDtestData(false);

            var sb = new System.Text.StringBuilder();
            var idx = 0;
            foreach (DataSet1.K4EE_Component_Reel_RegExRuleRow dr in this.dataSet1.K4EE_Component_Reel_RegExRule)
            {
                var pattern = dr.Pattern;// tbPattern.Text.Trim();
                var grps = dr.Groups;// tbGroups.Text.Trim();

                if (dr.IsEnable == false)
                {
                    sb.AppendLine($"####{++idx} {dr.Description} - disble");
                    continue;
                }

                var regx = new Regex(pattern, RegexOptions.IgnoreCase, new TimeSpan(0, 0, 10));
                if (regx.IsMatch(bcd))
                {
                    sb.AppendLine($"####{++idx} {dr.Description}");
                    var matchs = regx.Matches(bcd);

                    foreach (System.Text.RegularExpressions.Match mat in matchs)
                    {

                        var grpstr = this.tbGroups.Text.Trim().Split(',');
                        foreach (var matchdata in grpstr)
                        {
                            var grpname = matchdata.Split('=')[0];
                            var grpno = matchdata.Split('=')[1].toInt();
                            if (grpno <= mat.Groups.Count)
                            {
                                var data = mat.Groups[grpno];
                                sb.AppendLine($"{grpname}={data.Value}");
                            }
                        }
                    }
                }
                else
                {
                    sb.AppendLine($"####{++idx} {dr.Description} - No Pattern\n{pattern}");
                }
            }

            UTIL.MsgI(sb.ToString());


        }

        private void cmbModelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            var title = cmbModelList.Text;
            if (title.isEmpty()) title = PUB.Result.vModel.Title;
            RefreshList(title);
        }

        private string ChoiceModelName()
        {
            var cmb = new ComboBox();
            cmb.Items.Clear();
            foreach (var dr in PUB.mdm.dataSet.OPModel.OrderBy(t => t.Title))
                cmb.Items.Add(dr.Title);

            using (var f = new Form())
            {
                var lb = new Label()
                {
                    Text = "Select Model",
                    Dock = DockStyle.Top
                };
                var pan = new Panel()
                {
                    Dock = DockStyle.Bottom,
                    Height = 50,
                };
                var butok = new Button
                {
                    Text = "OK",
                    Width = 160,
                    Dock = DockStyle.Fill,
                };
                var butng = new Button
                {
                    Text = "Cancel",
                    Width = 160,
                    Dock = DockStyle.Right,
                };
                butok.Click += (s1, e1) =>
                {
                    f.DialogResult = DialogResult.OK;
                };
                butng.Click += (s1, e1) =>
                {
                    f.DialogResult = DialogResult.Cancel;
                };

                pan.Controls.Add(butok);
                pan.Controls.Add(butng);

                cmb.DropDownStyle = ComboBoxStyle.DropDownList;
                cmb.Dock = DockStyle.Top;
                f.StartPosition = FormStartPosition.CenterScreen;
                f.Width = 320;
                f.Height = 160;
                f.Text = "Select Model";
                f.MinimizeBox = false;
                f.MaximizeBox = false;
                f.Padding = new Padding(10);
                f.Controls.Add(pan);
                f.Controls.Add(cmb);
                f.Controls.Add(lb);

                if (f.ShowDialog() == DialogResult.OK)
                {
                    return cmb.Text;
                }
                else return string.Empty;
            }



        }

        private void btCopy_Click(object sender, EventArgs e)
        {
            try
            {
                var drv = this.bs.Current as DataRowView;
                if (drv == null)
                {
                    UTIL.MsgE("Please select an item to copy.");
                    return;
                }

                var sourceRow = drv.Row as DataSet1.K4EE_Component_Reel_RegExRuleRow;
                if (sourceRow == null) return;

                var inputDialog = ChoiceModelName(); // AR.UTIL.InputBox("Input ModelName", sourceRow.IsCustCodeNull() ? "" : sourceRow.CustCode);
                if (inputDialog.isEmpty()) return;
                var newModelName = inputDialog;

                //var inputDialog2 = AR.UTIL.InputBox("Input Description", sourceRow.IsDescriptionNull() ? "" : sourceRow.Description);
                //if (inputDialog2.Item1 == false) return;
                var newDescription = sourceRow.IsDescriptionNull() ? "" : sourceRow.Description;// inputDialog2.Item2;

                var tacheck = new DataSet1TableAdapters.K4EE_Component_Reel_RegExRuleTableAdapter();
                if (tacheck.CheckExsist(newModelName, newDescription) > 0)
                {
                    UTIL.MsgE("Name already exists");
                    return;
                }

                if (this.dataSet1.K4EE_Component_Reel_RegExRule.Where(t => t.CustCode.Equals(newModelName) && t.Description.Equals(newDescription)).Count() > 0)
                {
                    UTIL.MsgE("Name already exists");
                    return;
                }


                var newRow = this.dataSet1.K4EE_Component_Reel_RegExRule.NewK4EE_Component_Reel_RegExRuleRow();

                newRow.CustCode = newModelName;
                newRow.Pattern = sourceRow.IsPatternNull() ? "" : sourceRow.Pattern;
                newRow.Groups = sourceRow.IsGroupsNull() ? "" : sourceRow.Groups;
                newRow.Description = newDescription;
                newRow.IsEnable = sourceRow.IsEnable;
                newRow.IsIgnore = sourceRow.IsIgnore;
                newRow.Seq = sourceRow.Seq;
                newRow.Symbol = sourceRow.Symbol;
                newRow.IsTrust = sourceRow.IsTrust;
                newRow.IsAmkStd = sourceRow.IsAmkStd;
                this.dataSet1.K4EE_Component_Reel_RegExRule.AddK4EE_Component_Reel_RegExRuleRow(newRow);

                this.bs.MoveLast();
                UTIL.MsgI($"[{newModelName}-{newDescription}] Rule has been copied successfully.");
            }
            catch (System.Exception ex)
            {
                UTIL.MsgE($"Error occurred during copying: {ex.Message}");
            }
        }
    }
}
