using Microsoft.Extensions.Logging;
using SushiBarContracts.BindingModels;
using SushiBarContracts.BusinessLogicsContracts;
using System.Windows.Forms;

namespace SushiBar
{
    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 LoadData()
        {
            try
            {
                var list = _logic.ReadList(null);
                if (list != null)
                {
                    dataGridView.DataSource = list;
                    dataGridView.Columns["Id"].Visible = false;
                    dataGridView.Columns["ClientFio"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
                _logger.LogInformation("Load clients");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error load clients");
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void ButtonDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView.SelectedRows.Count == 1)
            {
                if (MessageBox.Show("Delete client?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
                    _logger.LogInformation("Delete client");
                    try
                    {
                        if (!_logic.Delete(new ClientBindingModel
                        {
                            Id = id
                        }))
                        {
                            throw new Exception("Error on deleting. Additional info below.");
                        }
                        LoadData();
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error delete client");
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
