using RealEstateTransactions.Entities;
using RealEstateTransactions.Repositories;

namespace RealEstateTransactions.Forms
{
    public partial class FormBuyer : Form
    {
        private readonly IBuyerRepository _repository;

        private int? _buyerId;

        public int Id
        {
            set
            {
                try
                {
                    var buyer = _repository.ReadBuyer(value);

                    if (buyer == null) throw new InvalidDataException(nameof(buyer));

                    textBoxFullName.Text = buyer.Full_name;
                    numericUpDownPassportSeries.Value = buyer.Passport_series;
                    numericUpDownPassportNumber.Value = buyer.Passport_number;

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

        public FormBuyer(IBuyerRepository repository)
        {
            InitializeComponent();
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        }

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

                if (_buyerId.HasValue)
                {
                    _repository.UpdateBuyer(CreateBuyer(_buyerId.Value));
                }
                else
                {
                    _repository.CreateBuyer(CreateBuyer(0));
                }

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

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

        private Buyer CreateBuyer(int id) => Buyer.CreateBuyer(id, textBoxFullName.Text,
            (int)numericUpDownPassportSeries.Value, (int)numericUpDownPassportNumber.Value);
    }
}