@using Task = System.Threading.Tasks.Task
@using Moonlight.App.Repositories.Servers
@using Moonlight.Shared.Components.FileManagerPartials
@using Moonlight.App.Database.Entities
@using Moonlight.App.Helpers
@using Moonlight.App.Helpers.Files
@using Moonlight.App.Services

@inject ServerRepository ServerRepository
@inject ServerService ServerService
@inject SmartTranslateService SmartTranslateService

<div class="col">
    <div class="card card-body p-0">
        <LazyLoader @ref="LazyLoader" Load="Load">
            <label class="me-2 form-label">
                <TL>Dll file</TL>
            </label>
            <table class="w-100">
                <tr>
                    <td class="w-100">
                        <input type="text" class="form-control disabled" disabled="" value="@(PathAndFile)"/>
                    </td>
                    <td>
                        <button @onclick="Show" class="btn btn-primary ms-2"><TL>Change</TL></button>
                    </td>
                </tr>
            </table>
        </LazyLoader>
    </div>
</div>

<FileSelectModal @ref="FileSelectModal"
                 Access="Access"
                 Filter="@(x => !x.IsFile || x.Name.EndsWith(".dll"))"
                 Title="@(SmartTranslateService.Translate("Select dll to execute on start"))"
                 OnlyFolder="false"
                 OnCancel="() => { return Task.CompletedTask; }"
                 OnSubmit="OnSubmit">
</FileSelectModal>

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

    private string PathAndFile;
    private FileAccess Access;
    
    private FileSelectModal FileSelectModal;
    private LazyLoader LazyLoader;

    protected override async Task OnInitializedAsync()
    {
        Access = await ServerService.CreateFileAccess(CurrentServer, null!);
    }

    private async Task Load(LazyLoader lazyLoader)
    {
        var v = CurrentServer.Variables.FirstOrDefault(x => x.Key == "MAIN_DLL");
        
        PathAndFile = v != null ? v.Value : "";

        await InvokeAsync(StateHasChanged);
    }

    private async Task Show()
    {
        await FileSelectModal.Show();
    }

    private async Task OnSubmit(string path)
    {
        var v = CurrentServer.Variables.FirstOrDefault(x => x.Key == "MAIN_DLL");

        if (v != null)
        {
            v.Value = path.TrimStart("/"[0]);
            
            ServerRepository.Update(CurrentServer);
        }
        
        await LazyLoader.Reload();
    }
}