using BarContracts.Attrubites;

namespace BarView
{
	public static class DataGridViewExtension
	{
		public static void FillAndConfigGrid<T>(this DataGridView Grid, List<T>? Data)
		{
			if (Data == null)
				return;

			Grid.DataSource = Data;

			var Type = typeof(T);
			var Properties = Type.GetProperties();
			
			foreach (DataGridViewColumn Column in Grid.Columns)
			{
				var Property = Properties.FirstOrDefault(x => x.Name == Column.Name);
				if (Property == null)
					throw new InvalidOperationException($"В типе {Type.Name} не найдено свойство с именем {Column.Name}");

				var Attribute = Property.GetCustomAttributes(typeof(ColumnAttribute), true)?.SingleOrDefault();
				if (Attribute == null)
					throw new InvalidOperationException($"Не найден атрибут типа ColumnAttribute для свойства {Property.Name}");

				if (Attribute is ColumnAttribute СolumnAttr)
				{
					Column.HeaderText = СolumnAttr.Title;
					Column.Visible = СolumnAttr.Visible;

					if (СolumnAttr.IsUseAutoSize)
					{
						Column.AutoSizeMode = (DataGridViewAutoSizeColumnMode)Enum.Parse(typeof(DataGridViewAutoSizeColumnMode), СolumnAttr.GridViewAutoSize.ToString());
					}
					else
					{
						Column.Width = СolumnAttr.Width;
					}
				}
			}
		}
	}
}
