using DressAtelierContracts.BindingModels;
using DressAtelierContracts.BusinessLogicContracts;
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 SewingDresses
{
    public partial class FormClients : Form
    {
        private readonly ILogger _logger;
        private readonly IClientLogic _logic;

        public FormClients(ILogger<FormClients> logger, IClientLogic logic)
        {
            InitializeComponent();
            _logger = logger;
            _logic = logic;
        }

        private void buttonClientDelete_Click(object sender, EventArgs e)
        {
            if(clientGridView.SelectedRows.Count == 1)
            {
                if(MessageBox.Show("Delete record?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int id = Convert.ToInt32(clientGridView.SelectedRows[0].Cells["ID"].Value);
                    _logger.LogInformation("Client deletion");
                    try
                    {
                        if(!_logic.Delete(new ClientBindingModel
                        {
                            ID = id
                        }))
                        {
                            throw new Exception("Deletion error. Extra information in logs.");
                        }
                        LoadData();
                    }
                    catch(Exception ex)
                    {
                        _logger.LogError(ex, "Client deletion error");
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

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

        private void LoadData()
        {
            try
            {
                var list = _logic.ReadList(null);

                if (list != null)
                {
                    clientGridView.DataSource = list;
                    clientGridView.Columns["ID"].Visible = false;
                    clientGridView.Columns["FullName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    clientGridView.Columns["Email"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    clientGridView.Columns["Password"].Visible = false;
                }
                _logger.LogInformation("Loading clients");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error loading clients");
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
