@namespace Oqtane.Modules.Admin.Tenants
@inherits ModuleBase
@inject ITenantService TenantService
@inject IAliasService AliasService

@if (tenants == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <Pager Items="@tenants">
        <Header>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th>Name</th>
        </Header>
        <Row>
            <td><ActionLink Action="Edit" Parameters="@($"id=" + context.TenantId.ToString())" /></td>
            <td><ActionDialog Header="Delete Tenant" Message="@("Are You Sure You Wish To Delete The " + context.Name + " Tenant?")" Action="Delete" Security="SecurityAccessLevel.Host" Class="btn btn-danger" OnClick="@(async () => await DeleteTenant(context))" Disabled="@(context.Name == Constants.MasterTenant)" /></td>
            <td>@context.Name</td>
        </Row>
    </Pager>

}

@code {
    private List<Tenant> tenants;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;

    protected override async Task OnParametersSetAsync()
    {
        tenants = await TenantService.GetTenantsAsync();
    }

    private async Task DeleteTenant(Tenant Tenant)
    {
        try
        {
            string message = string.Empty;
            var aliases = await AliasService.GetAliasesAsync();
            foreach (var alias in aliases)
            {
                if (alias.TenantId == Tenant.TenantId)
                {
                    message += ", " + alias.Name;
                }
            }
            if (string.IsNullOrEmpty(message))
            {
                await TenantService.DeleteTenantAsync(Tenant.TenantId);
                await logger.LogInformation("Tenant Deleted {Tenant}", Tenant);
                StateHasChanged();
            }
            else
            {
                AddModuleMessage("Tenant Cannot Be Deleted Until The Following Sites Are Deleted: " + message.Substring(2), MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting Tenant {Tenant} {Error}", Tenant, ex.Message);
            AddModuleMessage("Error Deleting Tenant", MessageType.Error);
        }
    }
}