using BarContracts.BindingModels;
using BarContracts.BusinessLogicContracts;
using BarContracts.BusinessLogicsContracts;
using BarContracts.DI;
using BarView.Forms;
using Microsoft.Extensions.Logging;

namespace BarView
{
	public partial class FormMain : Form
	{
		private readonly ILogger _logger;
		private readonly IOrderLogic _orderLogic;
		private readonly IReportLogic _reportLogic;
		private readonly IWorkProcess _workProcess;
		private readonly IBackUpLogic _backUpLogic;


		public FormMain(ILogger<FormMain> Logger, IOrderLogic OrderLogic, IReportLogic ReportLogic, IWorkProcess WorkProcess, IBackUpLogic backUpLogic)
		{
			InitializeComponent();

			_logger = Logger;
			_orderLogic = OrderLogic;
			_reportLogic = ReportLogic;
			_workProcess = WorkProcess;
			_backUpLogic = backUpLogic;
		}

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

		private void LoadData()
		{
			_logger.LogInformation("Загрузка заказов");

			try
			{
				DataGridView.FillAndConfigGrid(_orderLogic.ReadList(null));
				_logger.LogInformation("Загрузка заказов");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Ошибка загрузки заказов");
				MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormComponents>();

			if (Service is FormComponents Form)
			{
				Form.ShowDialog();
			}
		}

		private void CocktailsStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormCocktails>();

			if (Service is FormCocktails Form)
			{
				Form.ShowDialog();
			}
		}

		private void CreateOrderButton_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormCreateOrder>();

			if (Service is FormCreateOrder Form)
			{
				Form.ShowDialog();
				LoadData();
			}
		}

		private void TakeOrderInWorkButton_Click(object sender, EventArgs e)
		{
			if (DataGridView.SelectedRows.Count == 1)
			{
				int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);

				_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);

				try
				{
					var OperationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });

					if (!OperationResult)
					{
						throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
					}

					LoadData();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "Ошибка передачи заказа в работу");
					MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}

		}

		private void OrderReadyButton_Click(object sender, EventArgs e)
		{
			if (DataGridView.SelectedRows.Count == 1)
			{
				int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);

				_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);

				try
				{
					var OperationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });

					if (!OperationResult)
					{
						throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
					}

					LoadData();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "Ошибка отметки о готовности заказа");
					MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

		private void OrderDeliveredButton_Click(object sender, EventArgs e)
		{
			if (DataGridView.SelectedRows.Count == 1)
			{
				int id = Convert.ToInt32(DataGridView.SelectedRows[0].Cells["Id"].Value);

				_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);

				try
				{
					var OperationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });

					if (!OperationResult)
					{
						throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
					}

					_logger.LogInformation("Заказ №{id} выдан", id);
					LoadData();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
					MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}

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

		private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			using var Dialog = new SaveFileDialog { Filter = "docx|*.docx" };

			if (Dialog.ShowDialog() == DialogResult.OK)
			{
				_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = Dialog.FileName });
				MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
		}

		private void ComponentCocktailToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormReportCocktailComponents>();

			if (Service is FormReportCocktailComponents Form)
			{
				Form.ShowDialog();
			}
		}

		private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormReportOrders>();

			if (Service is FormReportOrders Form)
			{
				Form.ShowDialog();
			}
		}

		private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormClients>();

			if (Service is FormClients Form)
			{
				Form.ShowDialog();
			}
		}

		private void EmployersToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormImplementers>();

			if (Service is FormImplementers Form)
			{
				Form.ShowDialog();
			}
		}

		private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var ImplementerLogic = DependencyManager.Instance.Resolve<IImplementerLogic>();
			_workProcess.DoWork(ImplementerLogic, _orderLogic);

			MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		private void MailToolStripMenuItem_Click(object sender, EventArgs e)
		{
			var Service = DependencyManager.Instance.Resolve<FormMail>();

			if (Service is FormMail Form)
			{
				Form.ShowDialog();
			}
		}

		private void CreateBackupToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				if (_backUpLogic != null)
				{
					var FolderBrowser = new FolderBrowserDialog();
					if (FolderBrowser.ShowDialog() == DialogResult.OK)
					{
						_backUpLogic.CreateBackUp(new BackUpSaveBindingModel
						{
							FolderName = FolderBrowser.SelectedPath
						});
						MessageBox.Show("Бекап создан", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "Ошибка создания бэкапа", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		private void CreateBackupToolStripMenuItem_Click_1(object sender, EventArgs e)
		{

		}
	}
}
