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 FormExecutor : Form
    {
        private readonly IExecutorRepository _executorRepository;
        private int? _executorId;

        public int Id
        {
            set
            {
                try
                {
                    var executor = _executorRepository.ReadExecutorById(value);
                    if (executor == null)
                    {
                        throw new InvalidDataException(nameof(executor));
                    }
                    textBoxFullName.Text = executor.FullName;
                    dateTimePickerDateOfBirth.Value = executor.DateOfBirth;
                    numericUpDownHourlyRate.Value = executor.HourlyRate;
                    comboBoxJobTitle.SelectedItem = executor.JobTitles;
                    _executorId = value;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }
        public FormExecutor(IExecutorRepository executorRepository)
        {
            InitializeComponent();
            _executorRepository = executorRepository ?? throw new ArgumentNullException(nameof(executorRepository));

            comboBoxJobTitle.DataSource = Enum.GetValues(typeof(JobTitles));

        }

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

                if (_executorId.HasValue)
                {
                    _executorRepository.UpdateExecutor(CreateExecutor(_executorId.Value));
                }
                else
                {
                    _executorRepository.CreateExecutor(CreateExecutor(0));
                }
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при сохранении",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private Executor CreateExecutor(int id) => Executor.CreateEntity(id, textBoxFullName.Text, dateTimePickerDateOfBirth.Value, numericUpDownHourlyRate.Value, Entities.Enums.JobTitles.Analyst);
    }
}
