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

async function login(redirectTo = '/home')
{
	clear('innerHTML', ['username', 'password', 'login']);

	let username = document.getElementById('usernameInput').value;
	let password = document.getElementById('passwordInput').value;

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

	let response = await client.login(username, password);

	if (response.status == 200) {
		await client.notice.disconnect();
		await client.notice.connect();
		navigateTo(redirectTo);
	} else {
		let error = await response.json();
		fill_errors(error, "innerHTML");
	}
}

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

	async postInit()
	{
		let usernameField = document.getElementById('usernameInput');
		usernameField.addEventListener('keydown', ev => {
			if (ev.key === 'Enter')
				login(this.redirectTo);
		});
		usernameField.focus();
		let passwordField = document.getElementById('passwordInput');
		passwordField.addEventListener('keydown', ev => {
			if (ev.key === 'Enter')
				login(this.redirectTo);
		});
		document.getElementById('loginButton').onclick = _ => login(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'>Login</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='loginButton'>Login</button>
					<span class='text-danger my-auto mx-2' id='login'></span>
					<p class='ms-auto mt-auto'>No account yet? <a href='/register' data-link>Register</a></p>
				</div>
			</form>
		</div>
		`;
    }
}
