using RealEstateTransactions.Entities;
using RealEstateTransactions.Repositories;

namespace RealEstateTransactions.Forms
{
    public partial class FormDeal : Form
    {
        private readonly IDealRepository _repository;

        public FormDeal(IDealRepository repository, IApartmentRepository apartmentRepository,
            IBuyerRepository buyerRepository, IServicesRepository servicesRepository)
        {
            InitializeComponent();
            _repository = repository ?? throw new ArgumentNullException(nameof(repository));

            comboBoxApartmentId.DataSource = apartmentRepository.ReadApartments();
            comboBoxApartmentId.DisplayMember = "Id";
            comboBoxApartmentId.ValueMember = "Id";

            comboBoxFullName.DataSource = buyerRepository.ReadBuyers();
            comboBoxFullName.DisplayMember = "FullName";
            comboBoxFullName.ValueMember = "Id";

            ColumnService.DataSource = servicesRepository.ReadServices();
            ColumnService.DisplayMember = "Name";
            ColumnService.ValueMember = "Id";

            dateTimePickerDealDate.Value = DateTime.Now;
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBoxApartmentId.SelectedItem == null || comboBoxFullName.SelectedItem == null 
                    || dataGridView.RowCount < 1)
                    throw new Exception("Имеются не заполненные поля");

                _repository.CreateDeal(Deal.CreateDeal(0, (int)comboBoxApartmentId.SelectedValue!,
                    (int)comboBoxFullName.SelectedValue!, (float)numericUpDownDealPrice.Value, 
                    dateTimePickerDealDate.Value, CreateListFromDataGridView()));

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

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

        private List<ServicesDeal> CreateListFromDataGridView()
        {
            var list = new List<ServicesDeal>();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.Cells["ColumnService"].Value == null ||
                row.Cells["ColumnTimeSpan"].Value == null)
                {
                    continue;
                }
                list.Add(ServicesDeal.CreateServicesDeal((int)row.Cells["ColumnService"].Value,
                    0, Convert.ToDouble(row.Cells["ColumnTimeSpan"].Value)));
            }
            return list;
        }
    }
}