using ProjectItCompany.Entities;
using ProjectItCompany.Entities.Enums;
using ProjectItCompany.Repositories;
using ProjectItCompany.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProjectItCompany.Forms
{
    public partial class FormContract : Form
    {
        private readonly IContractRepository _contractRepository;

        public FormContract(IContractRepository contractRepository,
            IProjectRepository projectRepository, ICustomerRepository customerRepository)
        {
            InitializeComponent();
            _contractRepository = contractRepository ?? throw new ArgumentNullException(nameof(contractRepository));

            ColumnProject.DataSource = projectRepository.ReadProjects();
            ColumnProject.DisplayMember = "NameProject";
            ColumnProject.ValueMember = "Id";

            ColumnCustomer.DataSource = customerRepository.ReadCustomers();
            ColumnCustomer.DisplayMember = "NameCustomer";
            ColumnCustomer.ValueMember = "Id";

        }
        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewContract.RowCount < 1)
                {
                    throw new Exception("Имеются незаполненные поля");
                }
                _contractRepository.CreateContract(Contract.CreateOpeartion(0, DateTime.Now, 0, CreateListExecutorOnProject()));
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при сохранении",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private List<Entities.CustomerOnProject> CreateListExecutorOnProject()
        {
            var list = new List<Entities.CustomerOnProject>();
            foreach (DataGridViewRow row in dataGridViewContract.Rows)
            {
                if (row.Cells["ColumnProject"].Value == null ||
                row.Cells["ColumnCustomer"].Value == null)
                {
                    continue;
                }
                list.Add(Entities.CustomerOnProject.CreateElement(0,
                Convert.ToInt32(row.Cells["ColumnProject"].Value), Convert.ToInt32(row.Cells["ColumnCustomer"].Value), string.Empty));
            }
            return list;
        }

    }
}
