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

@inject ServerService ServerService
@inject ServerRepository ServerRepository
@inject ImageRepository ImageRepository
@inject ForgeService ForgeService
@inject SmartTranslateService TranslationService

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

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

    private Dictionary<string, string> Versions = new();
    private string CurrentVersion = "";


    private async Task Load(LazyLoader lazyLoader)
    {
        Versions = await ForgeService.GetVersions();
        
        var vars = CurrentServer.Variables;
        var versionVar = vars.FirstOrDefault(x => x.Key == "FORGE_VERSION");

        // Live migration
        if (versionVar == null)
        {
            CurrentServer.Variables.Add(new ()
            {
                Key = "FORGE_VERSION",
                Value = LatestVersion()
            });
            
            ServerRepository.Update(CurrentServer);
            
            versionVar = vars.First(x => x.Key == "FORGE_VERSION");
        }
        else
        {
            if (string.IsNullOrEmpty(versionVar.Value))
            {
                versionVar.Value = LatestVersion();
                ServerRepository.Update(CurrentServer);
            }
        }

        CurrentVersion = versionVar.Value;

        await InvokeAsync(StateHasChanged);
    }

    private string DisplayToData(string display)
    {
        return display
            .Replace("-recommended", "")
            .Replace("-latest", "") + "-" + Versions[display];
    }

    private string LatestVersion()
    {
        var versionsSorted = Versions.Keys
            .OrderByDescending(ParseHelper.MinecraftToInt);

        return DisplayToData(versionsSorted.First());
    }

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

        versionVar.Value = CurrentVersion;

    // This searches for the display name of a version using the constructed full version
        var version = ParseHelper.MinecraftToInt(
            Versions.First(
                x => DisplayToData(x.Key) == CurrentVersion).Key);
        
        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);
    }
}