using RealEstateTransactions.Entities;
using RealEstateTransactions.Repositories;

namespace RealEstateTransactions.Forms
{
    public partial class FormService : Form
    {
        private readonly IServicesRepository _repository;

        private int? _serviceId;

        public int Id
        {
            set
            {
                try
                {
                    var service = _repository.ReadService(value);

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

                    textBoxName.Text = service.Name;
                    numericUpDownPrice.Value = (decimal)service.Price;

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

        public FormService(IServicesRepository repository)
        {
            InitializeComponent();
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        }

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

                if (_serviceId.HasValue)
                {
                    _repository.UpdateService(CreateService(_serviceId.Value));
                }
                else
                {
                    _repository.CreateService(CreateService(0));
                }

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

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

        private Services CreateService(int id) => Services.CreateService(id, textBoxName.Text, (float)numericUpDownPrice.Value);
    }
}