using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using DatabaseImplement.Models;
using DataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp
{
    public partial class FormSupplier : Form
    {
        private readonly ILogger _logger;
        private readonly ISupplierLogic _logic;
        private Guid? _id;
        private Dictionary<Guid, (IProduct, int)> _supplierProducts;
        public Guid Id { set { _id = value; } }
        public FormSupplier(ILogger<FormSupply> logger, ISupplierLogic supplierLogic)
        {
            InitializeComponent();
            _logger = logger;
            _supplierProducts = new Dictionary<Guid, (IProduct, int)>();
            _logic = supplierLogic;
        }
        private void FormSupplier_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Загрузка изделия");
                try
                {
                    var view = _logic.ReadElement(new SupplierSearchModel
                    {
                        Id = _id.Value
                    });
                    if (view != null)
                    {
                        textBoxName.Text = view.Name;
                        _supplierProducts = view.AvailibleProducts ?? new Dictionary<Guid, (IProduct, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка загрузки изделия");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void LoadData()
        {
            _logger.LogInformation("Загрузка компонент изделия");
            try
            {
                if (_supplierProducts != null)
                {
                    dataGridView.Rows.Clear();
                    foreach (var pc in _supplierProducts)
                    {
                        dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.Name, pc.Value.Item2 });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка загрузки компонент изделия");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
               MessageBoxIcon.Error);
            }
        }

        private void buttonAddProduct_Click(object sender, EventArgs e)
        {
            var service = Program.ServiceProvider?.GetService(typeof(FormSupplierProduct));
            if (service is FormSupplierProduct form)
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    if (form.ProductModel == null)
                    {
                        return;
                    }
                    _logger.LogInformation("Добавление нового компонента");
                    if (_supplierProducts.ContainsKey(form.Id))
                    {
                        _supplierProducts[form.Id] = (form.ProductModel, form.Count);
                    }
                    else
                    {
                        _supplierProducts.Add(form.Id, (form.ProductModel, form.Count));
                    }
                    LoadData();
                }
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxName.Text))
            {
                MessageBox.Show("Заполните информацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (_supplierProducts == null || _supplierProducts.Count == 0)
            {
                MessageBox.Show("Заполните товары", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Сохранение изделия");
            try
            {
                var model = new SupplierBindingModel
                {
                    Id = _id ?? Guid.NewGuid(),
                    Name = textBoxName.Text,
                    AvailibleProducts = _supplierProducts,
                    Deals = Convert.ToInt32(numericUpDownDeals.Value),
                };
                var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
                if (!operationResult)
                {
                    throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                }
                MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка сохранения изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
