using CocktailWeb.Data;
using Microsoft.AspNetCore.Components.Web;

using Microsoft.EntityFrameworkCore;
namespace CocktailWeb.Pages.Settings
{
    partial class Machine
    {
        private DbDataContext? _DataContext;
        private List<Filler> Fillers { get; set; } = new();
        private List<Flasche> Flaschen { get; set; } = new();

        private Filler? SelectedFiller { get; set; }

        private Flasche? SelectedFlasche { get; set; }

        private ModalComponent modal = null!;

        protected override async Task OnInitializedAsync()
        {
            await ShowFillers();
        }

        private async Task ShowFillers()
        {
            _DataContext ??= await DataContextFactory.CreateDbContextAsync();
            if (_DataContext != null)
            {
                Fillers = await _DataContext.Fillers.Include(f => f.Flasche).OrderBy(f => f.Pos).ToListAsync();
                Flaschen = await _DataContext.Flaschen.OrderBy(fl => fl.Name).ToListAsync();
            }
        }

        public async Task OpenSelectionDialog(MouseEventArgs e, Filler f)
        {
            SelectedFiller = f;
            SelectedFlasche = f.Flasche;
            await modal.OpenModal();
        }


        public void SelectFlasche(MouseEventArgs e, Flasche? fl)
        {
            SelectedFlasche = fl;
        }

        private async Task SaveSelection(MouseEventArgs e)
        {
            if (SelectedFiller != null)
            {
                SelectedFiller.Flasche = SelectedFlasche;
                _DataContext ??= await DataContextFactory.CreateDbContextAsync();
                if (_DataContext != null)
                {
                    _DataContext.Fillers.Update(SelectedFiller);
                    await _DataContext.SaveChangesAsync();
                }
            }
            await CloseDialog();
        }

        private async Task CloseDialog()
        {
            SelectedFiller = null;
            SelectedFlasche = null;
            await modal.Close();
        }
    }
}
