using LibraryContracts.StorageContracts;
using LibraryDataModels.Dtos;
using LibraryDataModels.Views;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryWinFormsApp
{
	public partial class FormAuthors : Form
	{
		private IAuthorStorage _authorStorage;
		private List<AuthorView> _authors;
		public FormAuthors(IAuthorStorage authorStorage)
		{
			_authorStorage = authorStorage;
			_authors = new List<AuthorView>();
			InitializeComponent();
		}

		private void FormAuthors_Load(object sender, EventArgs e)
		{
			LoadData();
		}

		private void LoadData()
		{
			try
			{
				_authors = _authorStorage.GetFullList();
				if (_authors != null)
				{
					authorsTable.DataSource = _authors;
					authorsTable.Columns[0].Visible = false;
					authorsTable.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void authorsTable_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			var cellValue = (string)authorsTable.CurrentRow.Cells[1].EditedFormattedValue;
			if (!string.IsNullOrEmpty(cellValue))
			{
				var keyValue = Convert.ToInt32(authorsTable.CurrentRow.Cells[0].Value);
				if (keyValue != -1)
				{
					_authorStorage.Update(new AuthorDto()
					{
						Id = keyValue,
						Name = cellValue,
					});
				}
				else
				{
					_authorStorage.Insert(new AuthorDto()
					{
						Name = cellValue,
					});
				}
			}
			else
			{
				MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			LoadData();
		}

		private void authorsTable_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyData == Keys.Insert)
			{
				if (authorsTable.Rows.Count == 0)
				{
					_authors.Add(new AuthorView());
					authorsTable.DataSource = new BindingList<AuthorView>(_authors);
					authorsTable.CurrentCell = authorsTable.Rows[0].Cells[1];
					return;
				}
				if (authorsTable.Rows[authorsTable.Rows.Count - 1].Cells[1].Value != null)
				{
					_authors.Add(new AuthorView());
					authorsTable.DataSource = new BindingList<AuthorView>(_authors);
					authorsTable.CurrentCell = authorsTable.Rows[authorsTable.Rows.Count - 1].Cells[1];
					return;
				}
			}
			if (e.KeyData == Keys.Delete)
			{
				if (MessageBox.Show("Удалить выбранный элемент?", "Удаление",
					MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					_authorStorage.Delete(new AuthorDto() 
					{ 
						Id = Convert.ToInt32(authorsTable.CurrentRow.Cells[0].Value),
					});
					LoadData();
				}
			}
		}
	}
}