@using Moonlight.App.Services
@using Task = System.Threading.Tasks.Task
@using Microsoft.EntityFrameworkCore
@using Moonlight.App.Database.Entities
@using Moonlight.App.Repositories
@using Moonlight.App.Repositories.Servers

@inject ServerService ServerService
@inject ServerRepository ServerRepository
@inject ImageRepository ImageRepository
@inject PaperService PaperService
@inject SmartTranslateService TranslationService

<div class="col">
    <div class="card card-body">
        <LazyLoader Load="Load">
            <label class="mb-2 form-label"><TL>Minecraft version</TL></label>
            <select class="mb-2 form-select" @bind="InputVersion">
                @foreach (var version in Versions)
                {
                    if (version == Version)
                    {
                        <option value="@(version)" selected="">@(version)</option>
                    }
                    else
                    {
                        <option value="@(version)">@(version)</option>
                    }
                }
            </select>
            <label class="mb-2 form-label"><TL>Build version</TL></label>
            <select class="mb-2 form-select" @bind="InputBuild">
                @foreach (var build in Builds)
                {
                    if (build == Build)
                    {
                        <option value="@(build)" selected="">@(build)</option>
                    }
                    else
                    {
                        <option value="@(build)">@(build)</option>
                    }
                }
            </select>
            <WButton 
                OnClick="Save" 
                Text="@(TranslationService.Translate("Change"))" 
                WorkingText="@(TranslationService.Translate("Changing"))" 
                CssClasses="btn-primary"></WButton>
        </LazyLoader>
    </div>
</div>

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

    private string[] Versions;
    private string Version;

    private string[] Builds;
    private string Build;

    // Form
    
    private string InputVersion
    {
        get { return Version; }
        set
        {
            Version = value;
            RefreshBuilds();
            Build = Builds.First();
            InvokeAsync(StateHasChanged);
        }
    }

    private string InputBuild
    {
        get { return Build; }
        set { Build = value; }
    }

    private async Task RefreshVersions()
    {
        Versions = (await PaperService.GetVersions()).Reverse().ToArray();
    }

    private async Task RefreshBuilds()
    {
        Builds = (await PaperService.GetBuilds(Version)).Reverse().ToArray();
    }

    private async Task Load(LazyLoader lazyLoader)
    {
        var vars = CurrentServer.Variables;

        await RefreshVersions();

        Version = vars.First(x => x.Key == "MINECRAFT_VERSION").Value;
        Build = vars.First(x => x.Key == "BUILD_NUMBER").Value;

        if (string.IsNullOrEmpty(Version))
            Version = "latest";
        
        if (string.IsNullOrEmpty(Build))
            Version = "latest";

        if (Version == "latest") // Live migration
        {
            Version = Versions.First();

            CurrentServer.Variables.First(x => x.Key == "MINECRAFT_VERSION").Value = Version;
            ServerRepository.Update(CurrentServer);
        }

        await RefreshBuilds();

        if (Build == "latest") // Live migration
        {
            Build = Builds.First();
            
            CurrentServer.Variables.First(x => x.Key == "BUILD_NUMBER").Value = Build;
            ServerRepository.Update(CurrentServer);
        }

        await InvokeAsync(StateHasChanged);
    }

    private async Task Save()
    {
        CurrentServer.Variables.First(x => x.Key == "MINECRAFT_VERSION").Value = Version;
        CurrentServer.Variables.First(x => x.Key == "BUILD_NUMBER").Value = Build;
        
        ServerRepository.Update(CurrentServer);

        var versionWithoutPre = Version.Split("-")[0];

        if (versionWithoutPre.Count(x => x == "."[0]) == 1)
            versionWithoutPre += ".0";

        var version = int.Parse(versionWithoutPre.Replace(".", ""));
        
        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);
    }
}