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

public partial class FormPatient : Form
{
    private readonly IPatientRepository _patientRepository;
    private int? _patientId;

    public int Id
    {
        set
        {
            try
            {
                var patient =
                _patientRepository.ReadPatientById(value);
                if (patient == null)
                {
                    throw new
                    InvalidDataException(nameof(patient));
                }
                textBoxNamePatient.Text = patient.Name;
                textBoxSurnamePatient.Text = patient.Surname;
                textBoxTelephone.Text = patient.Telephone;
                numericUpDownNumMedCard.Value = patient.NumMedCard;

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

    public FormPatient(IPatientRepository patientRepository)
    {
        InitializeComponent();
        _patientRepository = patientRepository ??
            throw new ArgumentNullException(nameof(patientRepository));
    }

    private void ButtonSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(textBoxNamePatient.Text) ||
                string.IsNullOrWhiteSpace(textBoxSurnamePatient.Text) ||
                 string.IsNullOrWhiteSpace(textBoxTelephone.Text))
            {
                throw new Exception("Имеются незаполненные поля");
            }

            if (_patientId.HasValue)
            {
                _patientRepository.UpdatePatient(CreatePatient(_patientId.Value));
            }
            else
            {
                _patientRepository.CreatePatient(CreatePatient(0));
            }

            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Ошибка при сохранении",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

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

    private Patient CreatePatient(int id) =>
        Patient.CreateEntity(id, textBoxNamePatient.Text, textBoxSurnamePatient.Text,
            textBoxTelephone.Text, Convert.ToInt32(numericUpDownNumMedCard.Value));

}

