using Microsoft.Extensions.Logging;
using SushiBarBusinessLogic.BusinessLogics;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using SushiBarDataModels.Enums;

namespace SushiBar
{
    public partial class FormMain : Form
    {

        private readonly ILogger _logger;
        private readonly IOrderLogic _orderLogic;
        private readonly IReportLogic _reportLogic;
        private readonly IWorkProcess _workProcess;

        public FormMain(ILogger<FormMain> logger, 
            IOrderLogic orderLogic, 
            IReportLogic reportLogic,
            IWorkProcess workProcess)
        {
            InitializeComponent();
            _logger = logger;
            _orderLogic = orderLogic;
            _reportLogic = reportLogic;
            _workProcess = workProcess;
        }

        private void LoadData()
        {
            _logger.LogInformation("Load components");
            try
            {
                var list = _orderLogic.ReadList(null);
                if (list != null)
                {
                    dataGridView.DataSource = list;
                    dataGridView.Columns["SushiId"].Visible = false;
                    dataGridView.Columns["ClientId"].Visible = false;
                    dataGridView.Columns["ImplementerId"].Visible = false;
                    dataGridView.Columns["ClientFio"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error on load orders");
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ButtonCreateOrder_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
            if (service is FormCreateOrder form)
            {
                form.ShowDialog();
                LoadData();
            }
        }

        private void ButtonSubmit_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Order №{id}. Change status on -Submit", id);
                try
                {
                    var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel {
                        Id = id,
                        SushiId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["SushiId"].Value),
                        SushiName = dataGridView.SelectedRows[0].Cells["SushiName"].Value.ToString(),
                        ClientFio = dataGridView.SelectedRows[0].Cells["ClientFio"].Value.ToString(),
                        Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
                        Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
                        DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
                    });
                    if (!operationResult)
                    {
                        throw new Exception("Error on saving. Additional info below.");
                    }
                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error submit order");
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void ButtonReady_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Order №{id}. Change status on -Ready",id);
                try
                {
                    var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel {
                        Id = id,
                        SushiId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["SushiId"].Value),
                        SushiName = dataGridView.SelectedRows[0].Cells["SushiName"].Value.ToString() ?? "",
                        ClientFio = dataGridView.SelectedRows[0].Cells["ClientFio"].Value.ToString() ?? "",
                        Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString() ?? "Unknown"),
                        Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString() ?? "0"),
                        DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString() ?? ""),
                    });
                    if (!operationResult)
                    {
                        throw new Exception("Error on saving. Additional info below.");
                    }
                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error on change status");
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }

        private void ButtonIssue_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
                _logger.LogInformation("Order №{id}. Change status on -Issued", id);
                try
                {
                    var operationResult = _orderLogic.FinishOrder(new OrderBindingModel {
                        Id = id,
                        SushiId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["SushiId"].Value),
                        SushiName = dataGridView.SelectedRows[0].Cells["SushiName"].Value.ToString(),
                        Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
                        ClientFio = dataGridView.SelectedRows[0].Cells["ClientFio"].Value.ToString(),
                        Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
                        Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
                        DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
                    });
                    if (!operationResult)
                    {
                        throw new Exception("Error on saving. Additional info below.");
                    }
                    _logger.LogInformation("Order №{id} issued", id);
                    LoadData();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error on change status");
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

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

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

        private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
            if (service is FormComponents form)
            {
                form.ShowDialog();
            }
        }

        private void SushiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormSushiMoreThenOne));

            if (service is FormSushiMoreThenOne form)
            {
                form.ShowDialog();
            }
        }

        private void ListComponentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _reportLogic.SaveSushiToWordFile(new ReportBindingModel
                {
                    FileName = dialog.FileName
                });
                MessageBox.Show("Complete", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void ComponentsOnSushiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormSushiOnComponents));
            if (service is FormSushiOnComponents form)
            {
                form.ShowDialog();
            }
        }

        private void ListOrdersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
            if (service is FormReportOrders form)
            {
                form.ShowDialog();
            }
        }

        private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormClients));
            if (service is FormClients form)
            {
                form.ShowDialog();
            }
        }

        private void StartWorkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
            MessageBox.Show("Process work is started", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
            if (service is FormImplementers form)
            {
                form.ShowDialog();
            }
        }
    }
}
