using TypographyContracts.BindingModels;
using TypographyContracts.BusinessLogicsContracts;
using TypographyContracts.SearchModels;
using TypographyContracts.ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using System.Windows.Forms;

namespace TypographyView
{
    public partial class FormCreateOrder : Form
    {
        private readonly ILogger _logger;

        private readonly IPrintedLogic _logicIC;

        private readonly IOrderLogic _logicO;
        private readonly IClientLogic _logicClient;

        public FormCreateOrder(ILogger<FormCreateOrder> logger, IPrintedLogic logicIC, IOrderLogic logicO, IClientLogic logicClient)
        {
            InitializeComponent();
            _logger = logger;
            _logicIC = logicIC;
            _logicO = logicO;
            _logicClient = logicClient;
        }

        private void FormCreateOrder_Load(object sender, EventArgs e)
        {
            _logger.LogInformation("Loading printed for order");
            try
            {
                var printedList = _logicIC.ReadList(null);
                if (printedList != null)
                {
                    comboBoxPrinted.DisplayMember = "PrintedName";
                    comboBoxPrinted.ValueMember = "Id";
                    comboBoxPrinted.DataSource = printedList;
                    comboBoxPrinted.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during loading printed for order");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            _logger.LogInformation("Загрузка клиентов для заказа");
            try
            {
                var list = _logicClient.ReadList(null);
                if (list != null)
                {
                    comboBoxClient.DisplayMember = "ClientFIO";
                    comboBoxClient.ValueMember = "Id";
                    comboBoxClient.DataSource = list;
                    comboBoxClient.SelectedItem = null;
                }

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

        private void CalcSum()
        {
            if (comboBoxPrinted.SelectedValue != null && !string.IsNullOrEmpty(textBoxCount.Text))
            {
                try
                {
                    int id = Convert.ToInt32(comboBoxPrinted.SelectedValue);
                    var printed = _logicIC.ReadElement(new PrintedSearchModel { Id = id });
                    int count = Convert.ToInt32(textBoxCount.Text);
                    textBoxSum.Text = Math.Round(count * (printed?.Price ?? 0), 2).ToString();
                    _logger.LogInformation("Calculation of order sum");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Calculation of order sum error");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

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

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

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxCount.Text))
            {
                MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (comboBoxPrinted.SelectedValue == null)
            {
                MessageBox.Show("Выберите закуску", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (comboBoxClient.SelectedValue == null)
            {
                MessageBox.Show("Выберите клиента", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Order creation");
            try
            {
                var operationResult = _logicO.CreateOrder(new OrderBindingModel
                {
                    PrintedId = Convert.ToInt32(comboBoxPrinted.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, "Order creation error");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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