using RealEstateTransactions.Entities;
using RealEstateTransactions.Repositories;
using RealEstateTransactions.Entities.Enums;

namespace RealEstateTransactions.Forms
{
    public partial class FormApartment : Form
    {
        private readonly IApartmentRepository _repository;

        private int? _apartmentId;

        public int Id
        {
            set
            {
                try
                {
                    var apartment = _repository.ReadApartment(value);

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

                    foreach (FormFactorType elem in Enum.GetValues(typeof(FormFactorType)))
                    {
                        if ((elem & apartment.Form_factor_ID) != 0)
                            checkedListBoxFormFactor.SetItemChecked(checkedListBoxFormFactor.Items.IndexOf(elem), true);
                    }

                    comboBoxAgency.SelectedIndex = (int)apartment.Agency_ID;
                    numericUpDownArea.Value = (decimal)apartment.Area;
                    numericUpDownPricePerSM.Value = (decimal)apartment.Price_per_SM;
                    numericUpDownBasePrice.Value = (decimal)apartment.Base_price;
                    numericUpDownDesiredPrice.Value = (decimal)apartment.Desired_price;

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

        public FormApartment(IApartmentRepository repository)
        {
            InitializeComponent();
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));
            comboBoxAgency.DataSource = Enum.GetValues(typeof(AgencyType));

            foreach (var elem in Enum.GetValues(typeof(FormFactorType))) checkedListBoxFormFactor.Items.Add(elem);
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxAgency.SelectedIndex == -1 || checkedListBoxFormFactor.CheckedItems.Count == 0)
                {
                    throw new Exception("Имеются незаполненные поля");
                }
                
                if (_apartmentId.HasValue)
                {
                    _repository.UpdateApartment(CreateApartment(_apartmentId.Value));
                }
                else
                {
                    _repository.CreateApartment(CreateApartment(0));
                }

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

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

        private Apartment CreateApartment(int Id)
        {
            FormFactorType formFactorType = FormFactorType.None;
            foreach (FormFactorType elem in checkedListBoxFormFactor.CheckedItems) formFactorType |= elem;

            return Apartment.CreateApartment(Id,
            (AgencyType)comboBoxAgency.SelectedIndex, formFactorType,
            (float)numericUpDownArea.Value, (float)numericUpDownPricePerSM.Value,
            (float)numericUpDownBasePrice.Value, (float)numericUpDownDesiredPrice.Value);
        }

        private void NumericUpDownArea_ValueChanged(object sender, EventArgs e) =>
            numericUpDownBasePrice.Value = numericUpDownArea.Value * numericUpDownPricePerSM.Value;

        private void NumericUpDownPricePerSM_ValueChanged(object sender, EventArgs e) =>
            numericUpDownBasePrice.Value = numericUpDownArea.Value * numericUpDownPricePerSM.Value;
    }
}