using ProjectShoeShop.Entities;
using ProjectShoeShop.Repositories;

namespace ProjectShoeShop.Forms
{
    public partial class FormOrder : Form
    {
        private readonly IOrderRepository _orderRepository;
        public FormOrder(IOrderRepository orderRepository, IClientRepository clientRepository, IShoesRepository shoesRepository)
        {
            InitializeComponent();
            _orderRepository = orderRepository ??
                throw new ArgumentNullException(nameof(orderRepository));

            comboBox.DataSource = clientRepository.ReadClient();
            comboBox.DisplayMember = "Name";
            comboBox.ValueMember = "Id";

            ColumnShoe.DataSource = shoesRepository.ReadShoes();
            ColumnShoe.DisplayMember = "Name";
            ColumnShoe.ValueMember = "Id";
        }

        private void ButtonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboBox.SelectedIndex < 0 || dataGridView.RowCount < 1)
                {
                    throw new Exception("Имеется незаполненное поле");
                }

                _orderRepository.CreateOrder(Order.CreateOperation(0,(int)comboBox.SelectedValue!, DateTime.Now, CreateListOrderItemFromDataGrid()));

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

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private List<OrderItem> CreateListOrderItemFromDataGrid()
        {
            var list = new List<OrderItem>();
            foreach (DataGridViewRow row in dataGridView.Rows)
            {
                if (row.Cells["ColumnShoe"].Value == null ||
                row.Cells["Size"].Value == null ||
                row.Cells["ColumnNumberOfPairs"].Value == null)
                {
                    continue;
                }
                list.Add(OrderItem.CreateElement(0,
                    Convert.ToInt32(row.Cells["ColumnShoe"].Value),
                    Convert.ToInt32(row.Cells["ColumnNumberOfPairs"].Value), 
                    Convert.ToInt32(row.Cells["Size"].Value)));
            }
            return list;
        }
    }
}
