using AR;
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 fSetting_ErrorMessage : Form
	{
		
		public fSetting_ErrorMessage()
		{
			InitializeComponent();


			this.KeyDown += (s1, e1) =>
			{
				if (e1.KeyCode == Keys.Escape)
					this.Close();
				if (DateTime.Now > PUB.LastInputTime) PUB.LastInputTime = DateTime.Now;
			};
			this.MouseMove += (s1, e1) => { if (DateTime.Now > PUB.LastInputTime) PUB.LastInputTime = DateTime.Now; };
			this.FormClosing += FSetting_ErrorMessage_FormClosing;
		}

		private void FSetting_ErrorMessage_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.bsError.EndEdit();
			this.Validate();
			var chgs = this.dataSet1.ErrorDescription.GetChanges();
			if (chgs != null && chgs.Rows.Count > 0)
			{
				if (UTIL.MsgQ("There are unsaved changes. If you close now, these changes will be lost. Do you want to close the window?") != DialogResult.Yes)
				{
					e.Cancel = true;
					return;
				}
			}
		}

		private void __Load(object sender, EventArgs e)
		{
			this.dv1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
			this.dv1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

			RefreshError();
		}

		void RefreshError()
		{
			this.dataSet1.ErrorDescription.Clear();
			this.dataSet1.ErrorDescription.Merge(PUB.mdm.dataSet.ErrorDescription);
			this.dataSet1.AcceptChanges();

			//자료를 업데이트해준다.
			var ecodelist = Enum.GetValues(typeof(eECode));
			for (short valueI = 0; valueI < 255; valueI++)
			{
				eECode valu = (eECode)valueI;
				//short valueI = (short)valu;

				var dr = this.dataSet1.ErrorDescription.Where(t => t.Idx == valueI).FirstOrDefault();
				if (dr == null)
				{
					//이 값이 없는경우에는 추가하지 않는다
					if (valu.ToString() == valueI.ToString())
					{
						//두 이름이 같다면 존재하는 코드 값이다
					}
					else
					{
						var newdr = dataSet1.ErrorDescription.NewErrorDescriptionRow();
						newdr.Idx = valueI;
						newdr.Title = valu.ToString();
						newdr.EndEdit();
						this.dataSet1.ErrorDescription.AddErrorDescriptionRow(newdr);
					}
				}
				else
				{
					if (valu.ToString() == valueI.ToString())
					{
						//해당 값이 업어졌다
						dr.Title = "n/a";
						dr.EndEdit();
					}
					else
					{
						if (dr.Title.Equals(valu.ToString()) == false)
						{
							dr.Title = valu.ToString();
							dr.EndEdit();
						}
					}

				}
			}
			this.dataSet1.AcceptChanges();

		}


		private void toolStripButton1_Click(object sender, EventArgs e)
		{
			//다시생성한다.
			this.dataSet1.ErrorDescription.Clear();
			this.dataSet1.ErrorDescription.AcceptChanges();

			var db = PUB.mdm.dataSet.ErrorDescription;

			//자료를 업데이트해준다.
			var ecodelist = Enum.GetValues(typeof(eECode));
			for (short valueI = 0; valueI < 255; valueI++)
			{
				eECode valu = (eECode)valueI;
				
				//변환된 이름과 숫자이름이 같다면 enum 에 정의되지 않은 데이터이다.
				if(valu.ToString().Equals(valueI.ToString()))
				{
					continue;
				}

				//같은 이름으로 데이터를 검색
				var drT = db.Where(t => t.Title == valu.ToString()).FirstOrDefault();
				if(drT != null)
				{
					var newdr = dataSet1.ErrorDescription.NewErrorDescriptionRow();
					newdr.Idx = valueI;
					newdr.Title = valu.ToString();
					newdr.Description = drT.Description;
					this.dataSet1.ErrorDescription.AddErrorDescriptionRow(newdr);
				}
				else
				{
					//같은버호로 찾는다
					var drN = this.dataSet1.ErrorDescription.Where(t => t.Idx == valueI).FirstOrDefault();
					if(drN != null)
					{
						var newdr = dataSet1.ErrorDescription.NewErrorDescriptionRow();
						newdr.Idx = valueI;
						newdr.Title = valu.ToString();
						newdr.Description = drN.Description;
						this.dataSet1.ErrorDescription.AddErrorDescriptionRow(newdr);
					}
					else
					{
						//번호도 타이틀도 없다
						var newdr = dataSet1.ErrorDescription.NewErrorDescriptionRow();
						newdr.Idx = valueI;
						newdr.Title = valu.ToString();
						newdr.EndEdit();
						this.dataSet1.ErrorDescription.AddErrorDescriptionRow(newdr);
					}
				}
			}
			this.dataSet1.AcceptChanges();

		}


		private void arDatagridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0) return;
			if (e.ColumnIndex == 2 || e.ColumnIndex == 3)
			{
				var dv = sender as DataGridView;
				var str = string.Empty;
				var cell = dv.Rows[e.RowIndex].Cells[e.ColumnIndex];
				if (cell != null && cell.Value != null) str = cell.Value.ToString();
				var f = new Dialog.fMessageInput(str);
				if (f.ShowDialog() == DialogResult.OK)
				{
					cell.Value = f.value;
				}
			}
		}

		private void toolStripButton2_Click_1(object sender, EventArgs e)
		{
			this.bsError.EndEdit();
			this.Validate();

			this.dataSet1.AcceptChanges();

			PUB.mdm.dataSet.ErrorDescription.Clear();
			PUB.mdm.dataSet.Merge(this.dataSet1.ErrorDescription);
			PUB.mdm.dataSet.AcceptChanges();
			PUB.mdm.SaveModelE();

			UTIL.MsgI("Save completed");

			//DialogResult = DialogResult.OK;
		}

		private void toolStripButton3_Click(object sender, EventArgs e)
		{
			dv1.AutoResizeColumns();
		}

		private void exportCSVToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var sd = new SaveFileDialog();
			sd.Filter = "Tab-separated text file(*.txt)|*.txt";
			if (sd.ShowDialog() != DialogResult.OK) return;

			var sb = new System.Text.StringBuilder();
			foreach (var dr in dataSet1.ErrorDescription.Select("","idx"))
			{
				var desc = dr["Description"].ToString();
				desc = desc.Replace("\r", "").Replace("\n", "");
				sb.AppendLine($"{dr["Idx"].ToString()}\t{dr["Title"].ToString()}\t{desc}");
			}
			System.IO.File.WriteAllText(sd.FileName, sb.ToString(), System.Text.Encoding.Default);
		}
	}
}

