using BusinessLogic.BusinessLogic;
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using IronBarCode;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp
{
    public partial class FormProducts : Form
    {
        private Guid? _id;
        private readonly ILogger _logger;
        private readonly IProductLogic _productLogic;
        private readonly IReportLogic _reportLogic;
        private readonly BarcodeLogic _barcodeLogic;
        private BarcodeResults? _barcode;
        List<string> _mediaFiles;
        public FormProducts(ILogger<FormMain> logger, IProductLogic productLogic, IReportLogic reportLogic)
        {
            InitializeComponent();
            _productLogic = productLogic;
            _logger = logger;
            _barcodeLogic = new BarcodeLogic();
            _barcode = null;
            _mediaFiles = new List<string>();
            _reportLogic = reportLogic;
        }

        private void FormProducts_Load(object sender, EventArgs e)
        {
            LoadData();
            groupBoxCreateProduct.Hide();
            //groupBoxCreateProduct.Enabled = false;
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка товаров");
            try
            {
                var list = _productLogic.ReadList(null);
                if (list != null)
                {
                    dataGridView.DataSource = list;
                }
                _logger.LogInformation("Загрузка товаров");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка загрузки товаров");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonCreateProduct_Click(object sender, EventArgs e)
        {
            //надо сделать че нибудь с фронтом а то всё грустно
            groupBoxControls.Hide();
            //groupBoxControls.Enabled = false;
            groupBoxCreateProduct.Show();
            //groupBoxCreateProduct.Enabled = true;
        }

        private void buttonSaveProduct_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxName.Text))
            {
                MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(numericUpDownPrice.Value.ToString()))
            {
                MessageBox.Show("Укажите цену", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(numericUpDownAmount.Value.ToString()))
            {
                MessageBox.Show("Укажите кол-во", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Сохранение товара");
            try
            {
                var model = new ProductBindingModel
                {
                    Id = _id ?? Guid.Empty,
                    Name = textBoxName.Text,
                    Price = Convert.ToDouble(numericUpDownPrice.Value),
                    Amount = Convert.ToInt16(numericUpDownAmount.Value),
                    Rate = 0.0,
                    IsBeingSold = checkBoxIsSold.Checked,
                };
                var operationResult = _id.HasValue ? _productLogic.Update(model) : _productLogic.Create(model);
                if (!_id.HasValue)
                {
                    var lastProductCreated = _productLogic.ReadList(null).Last();
                    _barcodeLogic.CreateBarcode(new ProductBindingModel()
                    {
                        Id = lastProductCreated.Id,
                        Name = lastProductCreated.Name,
                    }, true);

                }
                _id = null;
                if (!operationResult)
                {
                    throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                }
                MessageBox.Show("Сохранение прошло успешно", "Сообщение",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка сохранения товара");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
               MessageBoxIcon.Error);
            }
            finally
            {
                LoadData();
                //groupBoxControls.Enabled = true;
                groupBoxControls.Show();
                //groupBoxCreateProduct.Enabled = false;
                groupBoxCreateProduct.Hide();
                textBoxName.Text = string.Empty;
                numericUpDownAmount.Value = 0;
                numericUpDownPrice.Value = 0;
                checkBoxIsSold.Checked = false;
            }
        }

        private void buttonUpdateProduct_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count != 1) return;
            _id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
            groupBoxControls.Hide();
            groupBoxCreateProduct.Show();
            _logger.LogInformation("Получение товара");
            var view = _productLogic.ReadElement(new ProductSearchModel
            {
                Id = _id.Value
            });
            textBoxName.Text = view.Name;
            numericUpDownPrice.Value = Convert.ToDecimal(view.Price);
            numericUpDownAmount.Value = view.Amount;
            checkBoxIsSold.Checked = view.IsBeingSold;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            _id = null;
            groupBoxControls.Show();
            //groupBoxControls.Enabled = false;
            groupBoxCreateProduct.Hide();
            //groupBoxCreateProduct.Enabled = true;
            textBoxName.Text = string.Empty;
            numericUpDownAmount.Value = 0;
            numericUpDownPrice.Value = 0;
            checkBoxIsSold.Checked = false;
        }

        private void buttonDeleteProduct_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                if (MessageBox.Show("Удалить запись?", "Вопрос",
               MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Guid id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
                    _logger.LogInformation("Удаление товара");
                    try
                    {
                        if (!_productLogic.Delete(new ProductBindingModel
                        {
                            Id = id
                        }))
                        {
                            throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
                        }
                        LoadData();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Ошибка удаления товара");
                        MessageBox.Show(ex.Message, "Ошибка",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void buttonGenerateBarCode_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                var barcode = _barcodeLogic.CreateBarcode(new ProductBindingModel()
                {
                    Id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value,
                    Name = Convert.ToString(dataGridView.SelectedRows[0].Cells["Name"].Value),
                }, true);
                pictureBox1.Image = barcode.Image;
                _barcode = BarcodeReader.Read($"product{barcode.Value}.png");
            }
        }

        private void buttonReadBarCode_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "Image Files(*.jpg; *.png; *.jpeg; *.gif; *.bmp)|*.jpg;*.png;*.jpeg;*.gif;*.bmp";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Image = new Bitmap(dialog.FileName);
                _barcode = BarcodeReader.Read(dialog.FileName);
                Debug.WriteLine(_barcode.ToList()[0]);
                try
                {
                    var product = _productLogic.ReadElement(new ProductSearchModel()
                    {
                        Id = new Guid(_barcode.ToList()[0].Text),
                    });
                    groupBoxControls.Hide();
                    groupBoxCreateProduct.Show();
                    _logger.LogInformation("Получение товара по штрихкоду");
                    textBoxName.Text = product.Name;
                    numericUpDownPrice.Value = Convert.ToDecimal(product.Price);
                    numericUpDownAmount.Value = product.Amount;
                    checkBoxIsSold.Checked = product.IsBeingSold;
                    _id = product.Id;
                }
                catch (Exception ex)
                {
                    _logger.LogInformation("Ошибка получения товара по штрихкоду");
                }
            }
        }

        private void медиаФайлыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormMediaFiles));
            if (service is FormMediaFiles form)
            {
                form.ShowDialog();
            }
        }

        private void dataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                if (!File.Exists($"product{dataGridView.SelectedRows[0].Cells["Id"].Value}.png"))
                {
                    var barcode = _barcodeLogic.CreateBarcode(new ProductBindingModel()
                    {
                        Id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value,
                        Name = Convert.ToString(dataGridView.SelectedRows[0].Cells["Name"].Value),
                    }, true);
                    pictureBox1.Image = barcode.Image;
                }
                else
                {
                    pictureBox1.Image = new Bitmap($"product{dataGridView.SelectedRows[0].Cells["Id"].Value}.png");
                }
            }
        }

        private void buttonPrintCheque_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count != 1) return;
            var service = Program.ServiceProvider?.GetService(typeof(FormPreviewPDF));
            if (service is FormPreviewPDF form)
            {
                var src = $"productcheque{dataGridView.SelectedRows[0].Cells["Id"].Value}.pdf";
                        try
                        {
                            _reportLogic.SaveProductToPdfFile(new ReportBindingModel
                            {
                                FileName = $"productcheque{dataGridView.SelectedRows[0].Cells["Id"].Value}.pdf",
                                ProductId = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value,
                            });
                            _logger.LogInformation("Сохранение чека о товаре");
                            MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Ошибка сохранения чека");
                            MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                form.src = System.IO.Path.GetFullPath(src);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IronPrint.Printer.PrintAsync(src);
                }
            }
        }
    }
}
