@page "/sys/register"
@using ImageBoardServerApp.Data.Repository
@using ImageBoardServerApp.Auth
@inject IJSRuntime js
@inject AuthenticationStateProvider authStateProvider
@inject NavigationManager navManager

<div class="login">
    <form>
        <RadzenFormField Text="Email" Variant="Variant.Outlined">
            <RadzenTextBox @bind-Value="@Email" />
        </RadzenFormField>
        <br/>
        <RadzenFormField Text="Password" Variant="Variant.Outlined">
            <RadzenPassword @bind-Value="@Password" />
        </RadzenFormField>
        <br/>
        <RadzenCheckBox @bind-Value=@is18 Name="is_18" />
        <RadzenLabel Text="I am atleast 18 Years old." Component="is_18" />
        <br/>
        <br/>
        <RadzenButton Click=@login Text="login" ButtonStyle="ButtonStyle.Secondary" />
    </form>
    <br/>
    <br/>
    <br/>
    @if (msg != null)
    {
        <span class="msg">@msg</span>
    }
</div>


@code {
    private string Email { get; set; }
    private string Password { get; set; }
    private bool is18 { get; set; }
    
    private string msg { get; set; }

    private bool verified;

    private async Task login()
    {
        if (!is18)
        {
            msg = "You have to be atleast 18 years old to register.";
            return;
        }
        if (!Email.Contains("@") || !Email.Contains("."))
        {
            msg = "This Email address is not valid!";
            return;
        }
        if (Password.Length < 6)
        {
            msg = "Your password has to be longer then 6 characters.";
            return;
        }
        Console.WriteLine("Registering...");
        UserData userToCreate = new UserData()
        {
            Email = Email,
            Password = BCrypt.Net.BCrypt.HashPassword(Password),
            Role = "User",
            TimeBanned = -1,
            LastUsedName = "Anonymous"
        };
        if (await UsersRepository.getUserByEmailAsync(Email) != null)
        {
            return;
        }
        
        await UsersRepository.createUserAsync(userToCreate);
        var user = await UsersRepository.getUserByEmailRawAsync(Email);
        if (user == null)
        {
            await js.InvokeVoidAsync("alert", "User does not exist");
            verified = false;
            return;
        }
        verified = BCrypt.Net.BCrypt.Verify(Password, user.Password);
        if (verified)
        {
            verified = true;
            var customAuthStateProvider = (CustomAuthenticationStateProvider)authStateProvider;
            await customAuthStateProvider.UpdateAuthenticationStateAsync(user);
            navManager.NavigateTo("/", true);
            return;
        }
        await js.InvokeVoidAsync("alert", $"Wrong Password");
    }
}