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

public partial class FormDoctor : Form
{
    private readonly IDoctorRepository _doctorRepository;
    private int? _doctorId;

    public int Id
    {
        set
        {
            try
            {
                var doctor =
                _doctorRepository.ReadDoctorById(value);
                if (doctor == null)
                {
                    throw new
                    InvalidDataException(nameof(doctor));
                }
                textBoxNameDoctor.Text = doctor.Name;
                textBoxSurnameDoctor.Text = doctor.Surname;
                comboBoxDoctorArea.SelectedItem = doctor.DoctorArea;
                _doctorId = value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }

    public FormDoctor(IDoctorRepository doctorRepository)
    {
        InitializeComponent();
        _doctorRepository = doctorRepository ??
            throw new ArgumentNullException(nameof(doctorRepository));
        comboBoxDoctorArea.DataSource = Enum.GetValues(typeof(Area));
    }

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

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

    private Doctor CreateDoctor(int id) =>
        Doctor.CreateEntity(id, textBoxNameDoctor.Text, textBoxSurnameDoctor.Text,
                (Area)comboBoxDoctorArea.SelectedItem!);

}

