@using Moonlight.App.Services
@using Microsoft.EntityFrameworkCore
@using Moonlight.App.Database.Entities
@using Moonlight.App.Repositories
@using Moonlight.App.Repositories.Servers
@using Moonlight.App.Helpers
@using Moonlight.App.Services.Minecraft

@inject ServerService ServerService
@inject ServerRepository ServerRepository
@inject ImageRepository ImageRepository
@inject FabricService FabricService
@inject SmartTranslateService TranslationService

<div class="col">
    <div class="card card-body p-0">
        <LazyLoader Load="Load">
            <table class="w-100">
                <tr>
                    <td colspan="2">
                        <label class="form-label mb-0">
                            <TL>Fabric version</TL>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td class="w-100" colspan="2">
                        <input class="mb-2 form-control" disabled="" value="@(FabricVersion)"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <label class="form-label mb-0">
                            <TL>Fabric loader version</TL>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td class="w-100" colspan="2">
                        <input class="mb-2 form-control" disabled="" value="@(LoaderVersion)"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <label class="form-label mb-0">
                            <TL>Minecraft version</TL>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td class="w-100" colspan="2">
                        <select class="mb-2 form-select" @bind="CurrentVersion">
                            @foreach (var version in Versions)
                            {
                                if (version == CurrentVersion)
                                {
                                    <option value="@(version)" selected="">@(version)</option>
                                }
                                else
                                {
                                    <option value="@(version)">@(version)</option>
                                }
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td class="w-100"></td>
                    <td>
                        <WButton
                            OnClick="Save"
                            Text="@(TranslationService.Translate("Change"))"
                            WorkingText="@(TranslationService.Translate("Changing"))"
                            CssClasses="btn-primary mt-2">
                        </WButton>
                    </td>
                </tr>
            </table>
        </LazyLoader>
    </div>
</div>

@code
{
    [CascadingParameter]
    public Server CurrentServer { get; set; }

    private string[] Versions = Array.Empty<string>();
    private string CurrentVersion = "";

    private string FabricVersion = "";
    private string LoaderVersion = "";


    private async Task Load(LazyLoader lazyLoader)
    {
    // Fabric version

        var fabricVersion = LiveMigrateVar(
            "FABRIC_VERSION",
            await FabricService.GetLatestInstallerVersion(),
            true
            );

        FabricVersion = fabricVersion.Value;

    // Fabric loader version

        var loaderVersion = LiveMigrateVar(
            "LOADER_VERSION",
            await FabricService.GetLatestLoaderVersion(),
            true
            );

        LoaderVersion = loaderVersion.Value;

    // Minecraft versions

        Versions = await FabricService.GetGameVersions();

        var mcVersion = LiveMigrateVar(
            "MC_VERSION",
            Versions.First()
            );

        CurrentVersion = mcVersion.Value;

        await InvokeAsync(StateHasChanged);
    }

    private ServerVariable LiveMigrateVar(string key, string value, bool overwrite = false)
    {
        var v = CurrentServer.Variables.FirstOrDefault(x => x.Key == key);

        if (v == null)
        {
            CurrentServer.Variables.Add(new()
            {
                Key = key,
                Value = value
            });

            ServerRepository.Update(CurrentServer);

            return CurrentServer.Variables.First(x => x.Key == key);
        }
        else
        {
            if (string.IsNullOrEmpty(v.Value) || overwrite)
            {
                v.Value = value;

                ServerRepository.Update(CurrentServer);
            }

            return v;
        }
    }

    private async Task Save()
    {
        var vars = CurrentServer.Variables;
        var versionVar = vars.First(x => x.Key == "MC_VERSION");

        versionVar.Value = CurrentVersion;

    // This searches for the display name of a version using the constructed full version
        var version = ParseHelper.MinecraftToInt(CurrentVersion);

        var serverImage = ImageRepository
            .Get()
            .Include(x => x.DockerImages)
            .First(x => x.Id == CurrentServer.Image.Id);

        var dockerImages = serverImage.DockerImages;

        var dockerImageToUpdate = dockerImages.Last();

        if (version < 1130)
        {
            dockerImageToUpdate = dockerImages.First(x => x.Name.Contains("8"));
        }

        if (version >= 1130)
        {
            dockerImageToUpdate = dockerImages.First(x => x.Name.Contains("11"));
        }

        if (version >= 1170)
        {
            dockerImageToUpdate = dockerImages.First(x => x.Name.Contains("16"));
        }

        if (version >= 1190)
        {
            dockerImageToUpdate = dockerImages.First(x => x.Name.Contains("17"));
        }

        CurrentServer.DockerImageIndex = dockerImages.IndexOf(dockerImageToUpdate);

        ServerRepository.Update(CurrentServer);

        await ServerService.Reinstall(CurrentServer);
    }
}