@page "/admin/servers/images/view/{Id:int}/{Route?}"

@using Mappy.Net
@using MoonCoreUI.Services
@using MoonCore.Abstractions
@using Moonlight.Features.Servers.Entities
@using Microsoft.EntityFrameworkCore
@using Moonlight.Features.Servers.Models.Forms.Admin.Images
@using Moonlight.Features.Servers.UI.Components
@using Moonlight.Features.Servers.UI.ImageComponents

@inject Repository<ServerImage> ImageRepository
@inject ToastService ToastService

@attribute [RequirePermission(5002)]

<LazyLoader Load="Load">
    @if (Image == null)
    {
        <NotFoundAlert/>
    }
    else
    {
        <AdminImageViewNavigation Index="@GetIndex()" ImageId="@Id"/>

        <SmartForm Model="Form" OnValidSubmit="OnValidSubmit">

            <SmartRouter Route="@Route">
                <Route Path="/">
                    <ImageDetails Form="Form" />
                </Route>
                <Route Path="/power">
                    <ImagePower Form="Form" />
                </Route>
                <Route Path="/parsing">
                    <ParseConfigEditor @ref="ParseConfigEditor" InitialContent="@ParseConfigJson" />
                </Route>
                <Route Path="/variables">
                    <ImageVariables Image="Image" />
                </Route>
                <Route Path="/dockerimages">
                    <ImageDockerImages Image="Image" Form="Form" />
                </Route>
                <Route Path="/install">
                    <ImageInstall Form="Form" />
                </Route>
            </SmartRouter>

            <div class="mt-5 card card-body">
                <div class="text-end">
                    <button type="submit" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </SmartForm>
    }
</LazyLoader>

@code
{
    [Parameter] public int Id { get; set; }

    [Parameter] public string? Route { get; set; }

    private ServerImage? Image;
    private UpdateImageDetailedForm Form;

    //TODO: I need to create a @bind component so we dont need to do that
    private ParseConfigEditor? ParseConfigEditor;
    private string ParseConfigJson;

    private async Task Load(LazyLoader lazyLoader)
    {
        await lazyLoader.SetText("Loading image");

        Image = ImageRepository
            .Get()
            .Include(x => x.Variables)
            .Include(x => x.DockerImages)
            .FirstOrDefault(x => x.Id == Id);

        if (Image == null)
            return;

        Form = Mapper.Map<UpdateImageDetailedForm>(Image);
        ParseConfigJson = Image.ParseConfiguration;
    }

    private async Task OnValidSubmit()
    {
        Image = Mapper.Map(Image, Form)!;
        
        // Parse config
        if (ParseConfigEditor != null)
        {
            ParseConfigJson = await ParseConfigEditor.Get();
            
            // Validate the form and if its correct, copy the value for the update
            await ParseConfigEditor.Validate(); // this will throw an display exception if invalid
            Image.ParseConfiguration = ParseConfigJson;
        }

        ImageRepository.Update(Image);

        await ToastService.Success("Successfully updated image");
    }

    private int GetIndex()
    {
        if (string.IsNullOrEmpty(Route))
            return 0;

        var route = "/" + (Route ?? "");

        switch (route)
        {
            case "/power":
                return 1;
            case "/parsing":
                return 2;
            case "/variables":
                return 3;
            case "/dockerimages":
                return 4;
            case "/install":
                return 5;

            default:
                return 0;
        }
    }
}