using ProjectPatientAccounting.Repositories;
using Unity;
namespace ProjectPatientAccounting.Forms;

public partial class FormReceptions : Form
{
    private readonly IUnityContainer _container;
    private readonly IReceptionRepository _receptionRepository;

    public FormReceptions(IUnityContainer container, IReceptionRepository receptionRepository)
    {
        InitializeComponent();
        _container = container ??
        throw new ArgumentNullException(nameof(container));
        _receptionRepository = receptionRepository ??
            throw new ArgumentNullException(nameof(receptionRepository));
    }

    private void FormReceptions_Load(object sender, EventArgs e)
    {
        try
        {
            LoadList();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при загрузке",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void LoadList() => dataGridViewReceptions.DataSource =
        _receptionRepository.ReadReceptions();

    private bool TryGetIdentifierFromSelectedRow(out int id)
    {
        id = 0;
        if (dataGridViewReceptions.SelectedRows.Count < 1)
        {
            MessageBox.Show("Нет выбранной записи", "Ошибка",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        id = Convert.ToInt32(dataGridViewReceptions.SelectedRows[0].Cells["Id"].Value);
        return true;
    }

    private void ButtonAdd_Click(object sender, EventArgs e)
    {
        try
        {
            _container.Resolve<FormReception>().ShowDialog();
            LoadList();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при добавлении",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ButtonDel_Click(object sender, EventArgs e)
    {
        if (!TryGetIdentifierFromSelectedRow(out var findId))
        {
            return;
        }
        if (MessageBox.Show("Удалить запись?", "Удаление",
        MessageBoxButtons.YesNo) != DialogResult.Yes)
        {
            return;
        }
        try
        {
            _receptionRepository.DeleteReception(findId);
            LoadList();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при удалении",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
