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

@inject ServerRepository ServerRepository
@inject ImageRepository ImageRepository
@inject SmartTranslateService TranslationService

<div class="col">
    <div class="card card-body p-0">
        <LazyLoader @ref="LazyLoader" Load="Load">
            <label class="mb-2 form-label"><TL>Python version</TL></label>
            <table class="w-100">
                <tr>
                    <td class="w-100">
                        <select @bind="ImageIndex" class="form-select">
                            @foreach (var image in DockerImages)
                            {
                                if (image.Id == SelectedImage.Id)
                                {
                                    <option value="@(image.Id)" selected="selected">
                                        @(ParseHelper.FirstPartStartingWithNumber(image.Name))
                                    </option>
                                }
                                else
                                {
                                    <option value="@(image.Id)">
                                        @(ParseHelper.FirstPartStartingWithNumber(image.Name))
                                    </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 LazyLoader LazyLoader;
    private List<DockerImage> DockerImages;
    private DockerImage SelectedImage;

    private int ImageIndex
    {
        get => SelectedImage.Id;
        set { SelectedImage = DockerImages.First(x => x.Id == value); }
    }

    private Task Load(LazyLoader lazyLoader)
    {
        var image = ImageRepository
            .Get()
            .Include(x => x.DockerImages)
            .First(x => x.Id == CurrentServer.Image.Id);

        DockerImages = image.DockerImages;

        SelectedImage = DockerImages[CurrentServer.DockerImageIndex];
        
        return Task.CompletedTask;
    }

    private async Task Save()
    {
        CurrentServer.DockerImageIndex = DockerImages.IndexOf(SelectedImage);

        ServerRepository.Update(CurrentServer);
        
        await LazyLoader.Reload();
    }
}