using LDBproject.Entities;
using LDBproject.Repositories;

namespace LDBproject.AdditionalForms;

public partial class CustomerF : Form
{
    private readonly ICustomerCardsRep _customeRepository;
    private int? _custID;

    public CustomerF(ICustomerCardsRep customeR)
    {
        InitializeComponent();
        _customeRepository = customeR ?? throw new ArgumentNullException(nameof(customeR));
    }

    public int ID
    {
        set
        {
            try
            {
                var reader = _customeRepository.GetCardByID(value);

                if (reader == null)
                {
                    throw new InvalidDataException(nameof(reader));
                }

                FIOEnterTb.Text = reader.FIO;
                BirthdayDTPicker.Value = reader.AgeBirthday;

                _custID = value;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "CustomerF [ Error : wrong data ]", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
    }

    private void SaveBtn_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(FIOEnterTb.Text)
                || BirthdayDTPicker.Value.Year < 1940)
            {
                throw new Exception("CustomerF [ Blank spaces were left, not enough information ]");
            }

            if (_custID.HasValue)
            {
                _customeRepository.UpdateCard(CreateCustomer(_custID.Value));
            }
            else
            {
                _customeRepository.AddCard(CreateCustomer(0));
            }

            Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "CustomerF [ Error : while saving ]",
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

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

    private CustomerCard CreateCustomer(int id)
    {
        return CustomerCard.AddCustomer(id, FIOEnterTb.Text, BirthdayDTPicker.Value);
    }
}