@page "/admin/domains/shared/new"

@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Moonlight.App.Repositories.Domains
@using CloudFlare.Client.Api.Zones
@using Moonlight.App.Database.Entities

@inject SharedDomainRepository SharedDomainRepository
@inject SmartTranslateService SmartTranslateService
@inject DomainService DomainService
@inject ToastService ToastService
@inject NavigationManager NavigationManager

@attribute [PermissionRequired(nameof(Permissions.AdminNewSharedDomain))]

<LazyLoader Load="Load" @ref="LazyLoader">
    <div class="row mb-5">
        <div class="card card-body">
            <div class="mx-4 mt-4 mb-6">               
                <div class="mb-4">
                    <label class="form-label">
                        <TL>Domain</TL>
                    </label>
                    <select @bind="DomainId" class="form-select">
                        @if (Zones.Any())
                        {
                            foreach (var zone in Zones)
                            {
                                <option value="@(zone.Id)">@(zone.Name)</option>
                            }
                        }
                        else
                        {
                            <option value="">
                                <TL>No domains available</TL>
                            </option>
                        }
                    </select>
                </div>
                <div class="float-end">
                    <WButton Text="@(SmartTranslateService.Translate("Add"))"
                             WorkingText="@(SmartTranslateService.Translate("Adding"))"
                             CssClasses="btn-success float-end"
                             OnClick="Add">
                    </WButton>
                </div>
            </div>
        </div>
    </div>    
</LazyLoader>

@code {
    private string DomainId = "";
    private Zone[] Zones;
    private SharedDomain[] SharedDomains;

    private LazyLoader LazyLoader;

    private async Task Load(LazyLoader lazyLoader)
    {
        Zones = await DomainService.GetAvailableDomains();

        SharedDomains = SharedDomainRepository.Get().ToArray();
    }
    
    private async Task Add()
    {
        if(string.IsNullOrEmpty(DomainId))
            return;

        var domain = Zones.First(x => x.Id == DomainId);

        var sd = new SharedDomain()
        {
            CloudflareId = domain.Id,
            Name = domain.Name
        };

        SharedDomainRepository.Add(sd);
        await ToastService.Success(SmartTranslateService.Translate("Shared domain successfully added"));

        NavigationManager.NavigateTo("/admin/domains/shared");
    }
}