using Microsoft.Extensions.Logging;
using SewingDressesContracts.BusinessLogicsContracts;
using SewingDressesContracts.BindingModels;
using SewingDressesDatabaseImplement.Models;
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 SewingDressesView
{
	public partial class ImplementsForm : Form
	{
		private readonly ILogger _logger;
		private readonly IImplementLogic _logic;
		public ImplementsForm(ILogger<ImplementsForm> logger, IImplementLogic logic)
		{
			InitializeComponent();
			_logger = logger;
			_logic = logic;
		}
		private void LoadData()
		{
			try
			{
				var list = _logic.ReadList(null);
				if (list != null)
				{
					dataGridView.DataSource = list;
					dataGridView.Columns["Id"].Visible = false;
				}
				_logger.LogInformation("Loading employees");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Error loading employees");
				MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		private void buttonCreate_Click(object sender, EventArgs e)
		{
			var service = Program.ServiceProvider?.GetService(typeof(ImplementForm));
			if (service is ImplementForm form)
			{
				if (form.ShowDialog() == DialogResult.OK)
				{
					LoadData();
				}
			}
		}

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

		private void buttonChange_Click(object sender, EventArgs e)
		{
			if (dataGridView.SelectedRows.Count == 1)
			{
				var service = Program.ServiceProvider?.GetService(typeof(ImplementForm));
				if (service is ImplementForm form)
				{
					form.ID = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
					if (form.ShowDialog() == DialogResult.OK)
					{
						LoadData();
					}
				}
			}
		}

		private void buttonDelete_Click(object sender, EventArgs e)
		{
			if (dataGridView.SelectedRows.Count == 1)
			{
				if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					try
					{
						_logger.LogInformation("Delete component: {ComponentName}- {Count}", dataGridView.SelectedRows[0].Cells[1].Value);
						_logic?.Delete(new ImplementBindingModel{ Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)});
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					LoadData();
				}
			}
		}

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