using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TelerikTestReal
{
	public class TestParEditorCollection
	{
		public BindingList<TestParEditorItem> Items { get; } = new BindingList<TestParEditorItem>();

		private int maxGridId = 0;

		public TestParEditorCollection()
		{
			Items.ListChanged += Items_ListChanged;
		}

		public void Add(TestParItem item)
		{
			var editorItem = new TestParEditorItem(item, ++maxGridId);
			Items.Add(editorItem);

			if (item.HasSubItems)
				AttachSubItems(editorItem);
		}

		public void Remove(TestParEditorItem editorItem)
		{
			DetachSubItems(editorItem);
			Items.Remove(editorItem);
		}

		private void AttachSubItems(TestParEditorItem editorItem)
		{
			if (editorItem.Item.SubItemsCount == 0)
				return;

			var names = GetSubItemNames(editorItem.Item.TestType);
			for (int i = 0; i < editorItem.Item.SubItemsCount; i++)
			{
				var subItem = editorItem.Item.SubItems[i];
				var name = (i < names.Length) ? names[i] : $"({i + 1})";
				var ed = new TestParEditorItem(subItem, ++maxGridId, editorItem.GridID, name);
				editorItem.SubItems.Add(ed);
				Items.Add(ed);
			}
		}

		private void DetachSubItems(TestParEditorItem editorItem)
		{
			foreach (var ed in editorItem.SubItems)
				Items.Remove(ed);
		}

		private string[] GetSubItemNames(TestType testType)
		{
			switch (testType)
			{
				case TestType.TestNitu:
					return new string[] { "Priemer", "Vyska", "Tvar", "Naklon" };
				case TestType.TestZatky:
					return new string[] { "Hlbka", "Naklon" };
				case TestType.TestKolika:
					return new string[] { "Vyska", "Priemer" };
				default:
					return null;
			}
		}

		private void Items_ListChanged(object sender, ListChangedEventArgs e)
		{
			if ((e.ListChangedType == ListChangedType.ItemChanged) && (e.PropertyDescriptor.Name == "TestType"))
			{
				HandleTestTypeChanged(Items[e.NewIndex]);
			}

			if(e.ListChangedType == ListChangedType.ItemAdded)
			{
				string subName = Items[e.NewIndex].SubItemName;
				// OK, fired	
			}
		}

		private void HandleTestTypeChanged(TestParEditorItem editorItem)
		{
			DetachSubItems(editorItem);
			AttachSubItems(editorItem);
		}
	}
}
