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

namespace ProjectShoeShop.Forms
{
    public partial class FormClient : Form
    {
        private readonly IClientRepository _clientRepository;
        private int? _clientId;

        public int Id
        {
            set
            {
                try
                {
                    var client = _clientRepository.ReadClientById(value);
                    if (client == null)
                    {
                        throw new InvalidDataException(nameof(client));
                    }

                    textBoxName.Text = client.Name;
                    _clientId = value;

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
        }
        public FormClient(ClientRepository clientRepository)
        {
            InitializeComponent();
            _clientRepository = clientRepository ??
                throw new ArgumentNullException(nameof(clientRepository));
        }

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

                if (_clientId.HasValue)
                {
                    _clientRepository.CreateClient(CreateClient(_clientId.Value));
                }
                else
                {
                    _clientRepository.CreateClient(CreateClient(0));
                }

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

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
        private Client CreateClient(int id) => Client.CreateEntity(id, textBoxName.Text);

    }
}
