using Common.Database;
using Common.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Administration
{
    public partial class Start : Form
    {
        private readonly IServiceProvider serviceProvider;
        public Start(IServiceProvider _serviceProvider)
        {
            serviceProvider = _serviceProvider;
            InitializeComponent();
        }

        private void AddProduct(object sender, EventArgs e)
        {
            using var window = serviceProvider.GetRequiredService<ProductAdd>();
            window.ShowDialog();

            if (window.DialogResult == DialogResult.OK)
                UpdateGridView<Product>();
        }

        private void ListProducts(object sender, EventArgs e)
        {
            title.Visible = true;
            title.Text = "Products";

            UpdateGridView<Product>();
        }
        private void ListOrders(object sender, EventArgs e)
        {
            title.Visible = true;
            title.Text = "Orders";

            UpdateGridView<Order>();
        }

        private void EditProduct(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dataGridView.CurrentRow?.DataBoundItem is not Product product)
                return;

            using var window = serviceProvider.GetRequiredService<ProductAdd>();
            window.Product = product;
            window.ShowDialog();

            if (window.DialogResult == DialogResult.OK)
                UpdateGridView<Product>();
        }

        private void UpdateGridView<T>() where T : Base
        {
            var database = serviceProvider.GetRequiredService<IDatabase>();
            dataGridView.DataSource = null;

            var data = database.List<T>();
            dataGridView.DataSource = data;

            dataGridView.Columns["ID"].Visible = false;

            if (typeof(T) == typeof(Product))
            {
                dataGridView.Columns["Image"].Visible = false;
            } else if (typeof(T) == typeof(Order))
            {
                dataGridView.Columns["Products"].Visible = false;
            }
        }
    }
}
