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

namespace Nlgp1.StageEditor.Controls
{
	public partial class LayerAdderControl : UserControl
	{
		private IEnumerable< int > validIndexList;

		public LayerAdderControl()
		{
			InitializeComponent();

			// デフォルトチップの設定を一時的になくす
			this.DefaultLabel.Visible = false;
			this.DefaultNumeric.Visible = false;
		}

		public void MapData_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			var stage = (StageNotify)sender ;
			if (e.PropertyName == "AddLayer") UpdateDefaultName(stage);
			if (e.PropertyName == "RemoveLayer") UpdateDefaultName(stage);
		}

		public void ChipGridData_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			var layer = (LayerNotify)sender;
			if (e.PropertyName == "Create") UpdateValidList(layer);
			if (e.PropertyName == "AddChipData") UpdateValidList(layer);
		}

		private void UpdateDefaultName(StageNotify stage)
		{
			var defaultLayerName = string.Format("layer{0:00}", stage.LayerList.Count);
			this.LayerNameTextBox.Text = defaultLayerName;
		}

		private void UpdateValidList(LayerNotify layer)
		{
			this.validIndexList = layer.ChipTable.Keys;
		}

		private void AddButton_Click(object sender, EventArgs e)
		{
			var name = LayerNameTextBox.Text;
			var defaultChipID = (int)DefaultNumeric.Value;

			var isValid = ValidateValue(name, defaultChipID);
			if (isValid == false) return;

			DefaultNumeric.Value = 0;

			OnAdd(name, defaultChipID);
		}

		private bool ValidateValue(string name, int defaultChipID)
		{
			var message = "";
			if (name == "")
			{
				message = "レイヤー名が設定されていません";
			}
			//else if (validIDList.Contains(defaultChipID) == false)
			//{
			//    message = "無効なデフォルトチップIDです";
			//}
			if (message != "")
			{
				MessageBox.Show(message, this.Name);
				return false;
			}

			return true;
		}

		#region AddEvent

		public event AddEventHander Add;

		private void OnAdd(string name, int defaultChipID)
		{
			if (Add == null) return;

			var e = new AddEventArgs(name, defaultChipID);
			Add(this, e);
		}

		public delegate void AddEventHander(object sender, AddEventArgs e);
		public class AddEventArgs : EventArgs
		{
			public string Name { get; private set; }
			public int DefaultChipID { get; private set; }
			public AddEventArgs(string name, int defaultChipID)
			{
				this.Name = name;
				this.DefaultChipID = defaultChipID;
			}
		}

		#endregion
	}
}
