using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PrecastConcretePlantView
{
    public partial class FormShop : Form
    {
        private readonly IShopLogic _logic;
        private readonly ILogger _logger;
        private int? _id;
        private Dictionary<int, (IReinforcedModel, int)> _listShops;
        public int Id { set { _id = value; } }
        public FormShop(ILogger<FormShop> logger, IShopLogic logic)
        {
            InitializeComponent();
            _logger = logger;
            _listShops = new();
            _logic = logic;
        }

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

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(comboBoxShop.Text))
            {
                MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(textBoxAddress.Text))
            {
                MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _logger.LogInformation("Сохранение магазина");
            try
            {
                var model = new ShopBindingModel
                {
                    Id = _id ?? 0,
                    Name = comboBoxShop.Text,
                    Address = textBoxAddress.Text,
                    DateOpening = textBoxDateOpening.Value.Date,
                    ReinforcedMaxCount = (int)VolumeNumericUpDown.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);
            }
        }

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

        private void FormShop_Load(object sender, EventArgs e)
        {
            if (_id.HasValue)
            {
                _logger.LogInformation("Загрузка магазина");
                try
                {
                    var view = _logic.ReadElement(new ShopSearchModel
                    {
                        Id = _id.Value
                    });
                    if (view != null)
                    {
                        comboBoxShop.Text = view.Name;
                        textBoxAddress.Text = view.Address;
                        textBoxDateOpening.Text = view.DateOpening.ToString();
                        VolumeNumericUpDown.Value = view.ReinforcedMaxCount;
                        _listShops = view.ShopReinforcedies ?? new Dictionary<int, (IReinforcedModel, int)>();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Ошибка загрузки магазина");
                    MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
        }
    }
}
