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


<h3 class="headLogin">Login to bulletbroards</h3>
<div class="login">
    <form>
        <RadzenTemplateForm TItem="Model" Data="model" Submit=@login>
                <RadzenStack Gap="1rem" Class="gapeing">
                    <RadzenFormField Text="Email" Variant="@vari">
                        <ChildContent>
                            <RadzenTextBox Name="Email" @bind-Value=@model.Email />
                        </ChildContent>
                        <Helper>
                            <RadzenRequiredValidator Component="Email" Text="First name is required." />
                        </Helper>
                    </RadzenFormField>
                    <RadzenFormField Text="Password" Variant="@vari">
                        <ChildContent>
                            <RadzenTextBox Name="Password" @bind-Value=@model.Password />
                        </ChildContent>
                        <Helper>
                            <RadzenRequiredValidator Component="Password" Text="Your Password" />
                        </Helper>
                    </RadzenFormField>
                    <RadzenButton ButtonType="ButtonType.Submit" Text="Login" ></RadzenButton>
                </RadzenStack>
            </RadzenTemplateForm>
    </form>
</div>

@code {
    private Variant vari = Variant.Outlined;

    private bool verified;
    
    class Model
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    Model model = new Model();

    private async Task login()
    {
        Console.WriteLine("loggin you in...");
        var user = await UsersRepository.getUserByEmailRawAsync(model.Email);
        if (user == null)
        {
            await js.InvokeVoidAsync("alert", "User does not exist");
            verified = false;
            return;
        }
        verified = BCrypt.Net.BCrypt.Verify(model.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");
    }
}