using SewingDressesContracts.BusinessLogicsContracts;
using SewingDressesContracts.BindingModels;
using SewingDressesContracts.SearchModels;
using Microsoft.Extensions.Logging;


namespace SewingDressesView
{
	public partial class OrderForm : Form
	{
		private readonly ILogger _logger;
		private readonly IDressLogic _logicD;
		private readonly IOrderLogic _logicO;
		private readonly IClientLogic _logicC;

		public OrderForm(ILogger<OrderForm> logger, IDressLogic logicD, IOrderLogic logicO, IClientLogic logicC)
		{
			InitializeComponent();
			_logger = logger;
			_logicD = logicD;
			_logicO = logicO;
			_logicC = logicC;
		}

		private void buttonCancel_Click(object sender, EventArgs e)
		{
			DialogResult = DialogResult.Cancel;
			Close();
		}

		private void buttonSave_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(textBoxCount.Text))
			{
				MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			if (comboBoxDress.SelectedValue == null)
			{
				MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			_logger.LogInformation("Создание заказа");
			try
			{
				var operationResult = _logicO.CreateOrder(new OrderBindingModel
				{
					DressId = Convert.ToInt32(comboBoxDress.SelectedValue),
					ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
					Count = Convert.ToInt32(textBoxCount.Text),
					Sum = Convert.ToDouble(textBoxSum.Text)
				});
				if (!operationResult)
				{
					throw new Exception("Ошибка при создании заказа. Дополнительная информация в логах.");
				}
				MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
				DialogResult = DialogResult.OK;
				Close();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Create order error");
				MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		private void CalcSum()
		{
			if (comboBoxDress.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
			{
				try
				{
					int id = Convert.ToInt32(comboBoxDress.SelectedValue);
					var dress = _logicD.ReadElement(new DressSearchModel
					{
						Id = id
					});
					int count = Convert.ToInt32(textBoxCount.Text);
					textBoxSum.Text = Math.Round(count * dress?.Price ?? 0, 2).ToString();
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, "Calculate sum order error");
					MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);

				}
			}
		}

		private void comboBoxDress_SelectedIndexChanged(object sender, EventArgs e)
		{
			CalcSum();
		}

		private void textBoxCount_TextChanged(object sender, EventArgs e)
		{
			CalcSum();
		}

		private void OrderForm_Load(object sender, EventArgs e)
		{
			try
			{
				var listD = _logicD.ReadList(null);
				if (listD != null)
				{
					comboBoxDress.DisplayMember = "DressName";
					comboBoxDress.ValueMember = "Id";
					comboBoxDress.DataSource = listD;
					comboBoxDress.SelectedItem = null;
					_logger.LogInformation("Load dress for order");
				}
				var listC = _logicC.ReadList(null);
				if (listC != null )
				{
					comboBoxClient.DisplayMember = "ClientFIO";
					comboBoxClient.ValueMember = "Id";
					comboBoxClient.DataSource = listC;
					comboBoxClient.SelectedItem = null;
					_logger.LogInformation("Load clients for order");
				}

			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "Load dress for order error");

			}
		}
	}
}
