import { client, navigateTo } from "../../index.js";
import { clear, fill_errors } from "../../utils/formUtils.js";
import AbstractNonAuthentifiedView from "../abstracts/AbstractNonAuthentified.js";

async function register(redirectTo = '/home')
{
	let username = document.getElementById("usernameInput").value;
	let password = document.getElementById("passwordInput").value;

	if (username === '' || password === '') {
		clear("innerHTML", ["username", "password"]);
		if (username === '')
			document.getElementById('username').innerHTML = 'This field may not be blank.';
		if (password === '')
			document.getElementById('password').innerHTML = 'This field may not be blank.';
		return;
	}

	let response_data = await client.account.create(username, password);

	if (response_data == null)
	{
		navigateTo(redirectTo);
		return;
	}

	clear("innerHTML", ["username", "password", 'register']);
	fill_errors(response_data, "innerHTML");
}

export default class extends AbstractNonAuthentifiedView {
    constructor(params, lastUrlBeforeLogin = '/home') {
        super(params, "Register", lastUrlBeforeLogin);
		this.redirectTo = lastUrlBeforeLogin;
	}

	async postInit()
	{
		let usernameField = document.getElementById('usernameInput');
		usernameField.addEventListener('keydown', ev => {
			if (ev.key === 'Enter')
				register(this.redirectTo);
		});
		usernameField.focus();
		let passwordField = document.getElementById('passwordInput');
		passwordField.addEventListener('keydown', ev => {
			if (ev.key === 'Enter')
				register(this.redirectTo);
		});
		document.getElementById("registerButton").onclick = _ => register(this.redirectTo);
	}

    async getHtml() {
        return `
		<div class='container-fluid'>
			<form class='border border-2 rounded bg-light-subtle mx-auto p-2 col-md-7 col-lg-4'>
				<h4 class='text-center fw-semibold mb-4'>Register</h4>
				<div class='form-floating mb-2'>
					<input type='text' class='form-control' id='usernameInput' placeholder='Username'>
					<label for='usernameInput'>Username</label>
					<span class='text-danger' id='username'></span>
				</div>
				<div class='form-floating'>
					<input type='password' class='form-control' id='passwordInput' placeholder='Password'>
					<label for='passwordInput'>Password</label>
					<span class='text-danger' id='password'></span>
				</div>
				<div class='d-flex'>
					<button type='button' class='btn btn-primary mt-3 mb-2' id='registerButton'>Register</button>
					<span class='text-danger my-auto mx-2' id='register'></span>
					<p class='ms-auto mt-auto'>Already have an account? <a href='/login' data-link>Login</a></p>
				</div>
			</form>
		</div>
        `;
    }
}
