using ProjectPatientAccounting.Entities;
using ProjectPatientAccounting.Entities.Enums;
using ProjectPatientAccounting.Repositories;
namespace ProjectPatientAccounting.Forms;

public partial class FormMedicament : Form
{
    private readonly IMedicamentRepository _medicamentRepository;
    private int? _medicamentId;

    public int Id
    {
        set
        {
            try
            {
                var medicament = _medicamentRepository.ReadMedicamentById(value);
                if (medicament == null)
                {
                    throw new InvalidDataException(nameof(medicament));
                }

                textBoxNameMedicament.Text = medicament.Name;
                textBoxDescription.Text = medicament.Description;
                comboBoxTypeMedicament.SelectedItem = medicament.TypeMedicament;

                _medicamentId = value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }

    public FormMedicament(IMedicamentRepository medicamentRepository)
    {
        InitializeComponent();
        _medicamentRepository = medicamentRepository ??
            throw new ArgumentNullException(nameof(medicamentRepository));
        comboBoxTypeMedicament.DataSource = Enum.GetValues(typeof(TypeMedicament));
    }

    private void ButtonSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(textBoxNameMedicament.Text) ||
                string.IsNullOrWhiteSpace(textBoxDescription.Text) ||
                    comboBoxTypeMedicament.SelectedIndex < 1)
            {
                throw new Exception("Имеются незаполненные поля");
            }
            if (_medicamentId.HasValue)
            {
                _medicamentRepository.UpdateMedicament(CreateMedicament(_medicamentId.Value));
            }
            else
            {
                _medicamentRepository.CreateMedicament(CreateMedicament(0));
            }
            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при сохранении",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ButtonCancel_Click(object sender, EventArgs e) => Close();

    private Medicament CreateMedicament(int id) => Medicament.CreateEntity(id,
        textBoxNameMedicament.Text, textBoxDescription.Text,
        (TypeMedicament)comboBoxTypeMedicament.SelectedItem!);

}
