using ProjectItCompany.Entities;
using ProjectItCompany.Repositories;
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 FormCustomer : Form
    {
        private readonly ICustomerRepository _customerRepository;
        private int? _customerId;
        public int Id
        {
            set
            {
                try
                {
                    var customer = _customerRepository.ReadCustomerById(value);
                    if (customer == null)
                    {
                        throw new InvalidDataException(nameof(customer));
                    }
                    textBoxNameCustomer.Text = customer.NameCustomer;
                    textBoxDescriptionCustomer.Text = customer.Description;
                    _customerId = value;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }


        public FormCustomer(ICustomerRepository customerRepository)
        {
            InitializeComponent();
            _customerRepository = customerRepository ?? throw new ArgumentNullException(nameof(customerRepository));
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(textBoxNameCustomer.Text) || string.IsNullOrWhiteSpace(textBoxDescriptionCustomer.Text))
                {
                    throw new Exception("Имеются незаполненные поля");
                }
                if (_customerId.HasValue)
                {
                    _customerRepository.UpdateCustomer(CreateCustomer(_customerId.Value));
                }
                else
                {
                    _customerRepository.CreateCustomer(CreateCustomer(0));
                }
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка при сохранении",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


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

        private Customer CreateCustomer(int id) => Customer.CreateEntity(id, textBoxNameCustomer.Text, textBoxDescriptionCustomer.Text);
    }
}
