@page "/options/libraries/edit"
@page "/options/libraries/edit/{id}"
@using songrequests_blazor.Data
@inject Microsoft.EntityFrameworkCore.IDbContextFactory<LocalDbContext> DataContextFactory
@inject NavigationManager nav;
<h3>Bibliothek bearbeiten</h3>

<EditForm Model="@libItem" OnValidSubmit="AddLibrary">
    <CustomValidation @ref="customValidation" />
    <DataAnnotationsValidator />
    <ValidationSummary />
    <div class="d-flex gap-3 mb-3">
        <div class="border border-2 rounded p-3 w-100">
            <div class="mb-3">
                <label class="form-label" for="libName">Name der Bibliothek</label>
                <input id="libName" name="libName" type="text" class="form-control" @bind="@libItem.Name" />
            </div>
            <div class="mb-3">
                <label class="form-label" for="libType">Bibliothekstyp</label>
                <select class="form-select" @bind="@libItem.Type">
                    @foreach (var tp in Enum.GetNames(typeof(Library.LibraryType)))
                    {
                        <option>@tp</option>
                    }
                </select>
            </div>
            @if (libItem.Type == Library.LibraryType.Local)
            {
                <div class="mb-3">
                    <label class="form-label" for="libPaths">Pfade</label>
                    <div class="input-group">
                        <input class="form-control" type="text" id="libPaths" @bind="@InputAddPath" />
                        <button type="button" class="btn btn-primary" @onclick="args => AddPathToLibray(InputAddPath)">Hinzufügen</button>
                    </div>
                    @if (AddPathMessage != null)
                    {
                        <label class="form-label alert-danger">@AddPathMessage</label>
                    }
                    <ul class="list-group">
                        @if (libItem.ScanPaths != null && libItem.ScanPaths.Count > 0)
                        {
                            @foreach (var lp in libItem.ScanPaths ?? [])
                            {
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    @lp
                                    <button type="button" class="btn btn-secondary" @onclick="args => RemovePathFromLibrary(lp)">Entfernen</button>
                                </li>
                            }
                        }
                        else
                        {
                            <li class="list-group-item text-secondary ">Keine Einträge</li>
                        }
                    </ul>
                </div>
            }
            <button type="submit" class="btn btn-primary">Speichern</button>
            <button type="button" class="btn btn-secondary" @onclick="Cancel">Abbrechen</button>
        </div>
    </div>
</EditForm>


@code {
    [Parameter]
    public string? id { get; set; }

    const string LISTURL = "/options/libraries";

    Library libItem { get; set; } = null!;
    string? InputAddPath { get; set; }

    string? AddPathMessage { get; set; }

    private CustomValidation? customValidation;

    protected override async Task OnInitializedAsync()
    {
        if (id != null)
        {
            using (LocalDbContext db = await DataContextFactory.CreateDbContextAsync())
            {
                libItem = db.Libraries.Single(lib => lib.Id == Convert.ToInt32(id));
            }
        }
        libItem ??= new();
    }

    private void AddPathToLibray(string path)
    {
        AddPathMessage = null;
        if (!System.IO.Path.Exists(path))
        {
            AddPathMessage = "Der angegebene Pfad existiert nicht.";
            return;
        }

        libItem.ScanPaths ??= new List<string>();
        if (libItem.ScanPaths.Contains(path))
        {
            AddPathMessage = "Der Pfad ist bereits in der Liste enthalten.";
            return;
        }
        libItem.ScanPaths.Add(path);
        InputAddPath = null;
    }

    private void RemovePathFromLibrary(string path)
    {
        AddPathMessage = null;
        libItem.ScanPaths?.Remove(path);
    }

    private bool CustomValidate()
    {
        customValidation?.ClearErrors();
        var errors = new Dictionary<string, List<string>>();

        if (libItem.Type == Library.LibraryType.Local && (libItem.ScanPaths == null || libItem.ScanPaths?.Count == 0))
        {
            errors.Add(nameof(libItem.Type), new() { "Type 'Local' is selected but no paths are specified." });
        }
        if (errors.Any())
        {
            customValidation?.DisplayErrors(errors);
            return false;
        }
        else
        {
            return true;
        }
    }

    private void Cancel()
    {
        nav.NavigateTo(LISTURL);
    }
    private async Task AddLibrary()
    {
        if (!CustomValidate()) return;
        if (libItem.Type != Library.LibraryType.Local) libItem.ScanPaths = null;

        using (LocalDbContext db = await DataContextFactory.CreateDbContextAsync())
        {
            db.Libraries.Add(libItem);
            await db.SaveChangesAsync();
        }
        nav.NavigateTo(LISTURL);
    }
}
