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

<table class="table table-borderless">
    <tr>
        <td>
            <Label For="name" HelpText="The name of the tenant">Name: </Label>
        </td>
        <td>
            @if (name == Constants.MasterTenant)
            {
                <input id="name" class="form-control" @bind="@name" readonly />
            }
            else
            {
                <input id="name" class="form-control" @bind="@name" />
            }
        </td>
    </tr>
    <tr>
        <td>
            <Label For="connectionstring" HelpText="The database connection string">Connection String: </Label>
        </td>
        <td>
            <textarea id="connectionstring" class="form-control" @bind="@connectionstring" rows="3" readonly></textarea>
        </td>
    </tr>

</table>
<button type="button" class="btn btn-success" @onclick="SaveTenant">Save</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">Cancel</NavLink>

@code {
    private int tenantid;
    private string name = string.Empty;
    private string connectionstring = string.Empty;
    private string schema = string.Empty;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Host;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            tenantid = Int32.Parse(PageState.QueryString["id"]);
            var tenant = await TenantService.GetTenantAsync(tenantid);
            if (tenant != null)
            {
                name = tenant.Name;
                connectionstring = tenant.DBConnectionString;
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Tenant {TenantId} {Error}", tenantid, ex.Message);
            AddModuleMessage("Error Loading Tenant", MessageType.Error);
        }
    }

    private async Task SaveTenant()
    {
        try
        {
            connectionstring = connectionstring.Replace("\\\\", "\\");
            var tenant = await TenantService.GetTenantAsync(tenantid);
            if (tenant != null)
            {
                tenant.Name = name;
                tenant.DBConnectionString = connectionstring;
                
                await TenantService.UpdateTenantAsync(tenant);
                await logger.LogInformation("Tenant Saved {TenantId}", tenantid);

                NavigationManager.NavigateTo(NavigateUrl());
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Saving Tenant {TenantId} {Error}", tenantid, ex.Message);
            AddModuleMessage("Error Saving Tenant", MessageType.Error);
        }
    }
}
