@namespace Oqtane.Modules.Admin.Roles
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IRoleService RoleService

<table class="table table-borderless">
    <tr>
        <td>
            <Label For="name" HelpText="Name Of The Role">Name:</Label>
        </td>
        <td>
            <input id="name" class="form-control" @bind="@_name" />
        </td>
    </tr>
    <tr>
        <td>
            <Label For="description" HelpText="A Short Description Of The Role Which Describes Its Purpose">Description:</Label>
        </td>
        <td>
            <textarea id="description" class="form-control" @bind="@_description" rows="5"></textarea>
        </td>
    </tr>
    <tr>
        <td>
            <Label For="isautoassigned" HelpText="Indicates Whether Or Not New Users Are Automatically Assigned To This Role">Auto Assigned?</Label>
        </td>
        <td>
            <select id="isautoassigned" class="form-control" @bind="@_isautoassigned">
                <option value="True">Yes</option>
                <option value="False">No</option>
            </select>
        </td>
    </tr>
</table>
<button type="button" class="btn btn-success" @onclick="SaveRole">Save</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">Cancel</NavLink>

@code { 
    private string _name = string.Empty;
    private string _description = string.Empty;
    private string _isautoassigned = "False";

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    private async Task SaveRole()
    {
        var role = new Role();
        role.SiteId = PageState.Page.SiteId;
        role.Name = _name;
        role.Description = _description;
        role.IsAutoAssigned = (_isautoassigned == null ? false : Boolean.Parse(_isautoassigned));
        role.IsSystem = false;

        try
        {
            role = await RoleService.AddRoleAsync(role);
            await logger.LogInformation("Role Added {Role}", role);

            NavigationManager.NavigateTo(NavigateUrl());
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Adding Role {Role} {Error}", role, ex.Message);
            AddModuleMessage("Error Adding Role", MessageType.Error);
        }
    }

}
