@namespace Oqtane.Modules.Admin.Users
@inherits ModuleBase
@inject IRoleService RoleService
@inject IUserService UserService
@inject IUserRoleService UserRoleService
@inject IStringLocalizer<Roles> Localizer

@if (userroles == null)
{
    <p><em>@Localizer["Loading..."]</em></p>
}
else
{
    <table class="table table-borderless">
        <tr>
            <td>
                <Label For="user" HelpText="The user you are assigning roles to" ResourceKey="User">User: </Label>
            </td>
            <td>
                <input id="user" class="form-control" @bind="@name" disabled />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="role" HelpText="Select a role" ResourceKey="Role">Role: </Label>
            </td>
            <td>
                <select id="role" class="form-control" @bind="@roleid">
                    <option value="-1">&lt;@Localizer["Select Role"]&gt;</option>
                    @foreach (Role role in roles)
                    {
                        <option value="@(role.RoleId)">@role.Name</option>
                    }
                </select>
            </td>
        </tr>
        <tr>
            <td>
                <Label For="effectiveDate" HelpText="The date that this role assignment is active" ResourceKey="EffectiveDate">Effective Date: </Label>
            </td>
            <td>
                <input id="effectiveDate" class="form-control" @bind="@effectivedate" />
            </td>
        </tr>
        <tr>
            <td>
                <Label For="expiryDate" HelpText="The date that this role assignment expires" ResourceKey="ExpiryDate">Expiry Date: </Label>
            </td>
            <td>
                <input id="expiryDate" class="form-control" @bind="@expirydate" />
            </td>
        </tr>
    </table>
    <button type="button" class="btn btn-success" @onclick="SaveUserRole">@Localizer["Save"]</button>
    <NavLink class="btn btn-secondary" href="@NavigateUrl()">@Localizer["Cancel"]</NavLink>

    <hr class="app-rule" />
    <p align="center">
        <Pager Items="@userroles">
            <Header>
                <th>@Localizer["Roles"]</th>
                <th>@Localizer["Effective"]</th>
                <th>@Localizer["Expiry"]</th>
                <th>&nbsp;</th>
            </Header>
            <Row>
                <td>@context.Role.Name</td>
                <td>@context.EffectiveDate</td>
                <td>@context.ExpiryDate</td>
                <td>
                    <ActionDialog Header="Remove Role" Message="@Localizer["Are You Sure You Wish To Remove This User From The {0} Role?", context.Role.Name]" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteUserRole(context.UserRoleId))" Disabled="@(context.Role.IsAutoAssigned || (context.Role.Name == RoleNames.Host && userid == PageState.User.UserId))" ResourceKey="DeleteUserRole" />
                </td>
            </Row>
        </Pager>
    </p>
}

@code {
    private int userid;
    private string name = string.Empty;
    private List<Role> roles;
    private int roleid = -1;
    private string effectivedate = string.Empty;
    private string expirydate = string.Empty;
    private List<UserRole> userroles;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            userid = Int32.Parse(PageState.QueryString["id"]);
            User user = await UserService.GetUserAsync(userid, PageState.Site.SiteId);
            name = user.DisplayName;
            if (UserSecurity.IsAuthorized(PageState.User, RoleNames.Host))
            {
                roles = await RoleService.GetRolesAsync(PageState.Site.SiteId, true);
                roles = roles.Where(item => item.Name != RoleNames.Everyone).ToList();
            }
            else
            {
                roles = await RoleService.GetRolesAsync(PageState.Site.SiteId);
            }
            await GetUserRoles();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading Roles {Error}", ex.Message);
            AddModuleMessage(Localizer["Error Loading Roles"], MessageType.Error);
        }
    }

    private async Task GetUserRoles()
    {
        try
        {
            userroles = await UserRoleService.GetUserRolesAsync(PageState.Site.SiteId);
            userroles = userroles.Where(item => item.UserId == userid).ToList();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading User Roles {UserId} {Error}", userid, ex.Message);
            AddModuleMessage(Localizer["Error Loading User Roles"], MessageType.Error);
        }
    }

    private async Task SaveUserRole()
    {
        try
        {
            if (roleid != -1)
            {
                var userrole = userroles.Where(item => item.UserId == userid && item.RoleId == roleid).FirstOrDefault();
                if (userrole != null)
                {
                    if (string.IsNullOrEmpty(effectivedate))
                    {
                        userrole.EffectiveDate = null;
                    }
                    else
                    {
                        userrole.EffectiveDate = DateTime.Parse(effectivedate);
                    }

                    if (string.IsNullOrEmpty(expirydate))
                    {
                        userrole.ExpiryDate = null;
                    }
                    else
                    {
                        userrole.ExpiryDate = DateTime.Parse(expirydate);
                    }
                    await UserRoleService.UpdateUserRoleAsync(userrole);
                }
                else
                {
                    userrole = new UserRole();
                    userrole.UserId = userid;
                    userrole.RoleId = roleid;

                    if (string.IsNullOrEmpty(effectivedate))
                    {
                        userrole.EffectiveDate = null;
                    }
                    else
                    {
                        userrole.EffectiveDate = DateTime.Parse(effectivedate);
                    }

                    if (string.IsNullOrEmpty(expirydate))
                    {
                        userrole.ExpiryDate = null;
                    }
                    else
                    {
                        userrole.ExpiryDate = DateTime.Parse(expirydate);
                    }

                    await UserRoleService.AddUserRoleAsync(userrole);
                }

                await logger.LogInformation("User Assigned To Role {UserRole}", userrole);
                AddModuleMessage(Localizer["User Assigned To Role"], MessageType.Success);
                await GetUserRoles();
                StateHasChanged();
            }
            else
            {
                AddModuleMessage(Localizer["You Must Select A Role"], MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Saving User Roles {UserId} {Error}", userid, ex.Message);
            AddModuleMessage(Localizer["Error Saving User Roles"], MessageType.Error);
        }
    }

    private async Task DeleteUserRole(int UserRoleId)
    {
        try
        {
            await UserRoleService.DeleteUserRoleAsync(UserRoleId);
            await logger.LogInformation("User Removed From Role {UserRoleId}", UserRoleId);
            AddModuleMessage(Localizer["User Removed From Role"], MessageType.Success);
            await GetUserRoles();
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Removing User From Role {UserRoleId} {Error}", UserRoleId, ex.Message);
            AddModuleMessage(Localizer["Error Removing User From Role"], MessageType.Error);
        }
    }
}
