console.log('user_select.js loaded');

// Get containers
let mainSelectionDiv = document.getElementById('mainSelect');
let pinPadModal = document.getElementById('pinPadModal');
let numpad = document.getElementById('numpad');

let pinInput1 = document.getElementById('pinInput1');
let pinInput2 = document.getElementById('pinInput2');
let pinInput3 = document.getElementById('pinInput3');
let pinInput4 = document.getElementById('pinInput4');

let pinError = document.getElementById('pinError');

let lastActivity = new Date().getTime();
let lastActivityTimeout = 1000 * 60 * 5; // 5 minutes

let currentUser = null;

document.addEventListener('click', function() {
	lastActivity = new Date().getTime();
});

setInterval(function() {
	let now = new Date().getTime();
	if(now - lastActivity > lastActivityTimeout) {
		window.location.href = '/';
	}
}, 1000);

// Attach event listeners to all numpad buttons
let numpadButtons = numpad.getElementsByTagName('button');
for(let i = 0; i < numpadButtons.length; i++) {
	let button = numpadButtons[i];
	button.addEventListener('click', handleNumberClick);
}

// On keyboard input for pinInputX jump to next input field
pinInput1.addEventListener('input', function() {
	if(pinInput1.value) {
		pinInput2.focus();
		// Update pinValue
		pinValue = pinInput1.value;
	}
});
pinInput2.addEventListener('input', function() {
	if(pinInput2.value) {
		pinInput3.focus();
		pinValue = pinInput1.value + pinInput2.value;
	}
}
);
pinInput3.addEventListener('input', function() {
	if(pinInput3.value) {
		pinInput4.focus();
		pinValue = pinInput1.value + pinInput2.value + pinInput3.value;
	}
});

pinInput4.addEventListener('input', function() {
	if(pinInput4.value) {
		pinValue = pinInput1.value + pinInput2.value + pinInput3.value + pinInput4.value;
		validatePin();
	}
});

let baseStruct = document.getElementById("baseStruct");

let globalData;

let pinValue = "";

// On load
document.addEventListener('DOMContentLoaded', async function() {
	let data = await returnTableDataByTableName('user');
	console.info(`Found ${data.count} users`);
	const result = data.result;
	globalData = result;

	for(let i = 0; i < result.length; i++) {
		let user = result[i];
		let userDiv = baseStruct.cloneNode(true);
		userDiv.id = `user_${user.id}`;
		userDiv.innerHTML = user.name;
		userDiv.addEventListener('click', handleUserClick);

		mainSelectionDiv.appendChild(userDiv);
	}
});


function handleUserClick(e) {
	let userDiv = e.target;
	let userId = userDiv.id.split('_')[1];
	console.log(`Clicked on user with id ${userId}`);
	let user = globalData.find(u => u.id == userId);
	currentUser = user;
	console.log(user);
	if(user.code) {
		pinPadModal.classList.add('is-active');
		// Automatically focus on the first input field
		pinInput1.focus();
	} else {
		pinValue = "0000";
		validatePin();
	}
}

function validatePin() {
	let pin = pinValue;
	let userId = currentUser.id;
	console.log(`Validating pin ${pinValue} for user ${userId}`);
	_api.get("/user/codecheck?code=" + pinValue + "&id=" + userId).then((response) => {
		if(response) {
			console.log("Pin is correct");
			pinPadModal.classList.remove('is-active');
			// Write a cookie
			document.cookie = `user=${userId}`;
			document.cookie = `name=${currentUser.name}`;
			window.location.href = `/product_select?user=${userId}`;
		} else {
			console.log("Pin is incorrect");
			pinValue = "";
			updatePinFields();
			createTemporaryNotification('Fehlerhafte PIN Eingabe!', 'is-danger');
		}
	});
}

function handleNumberClick(e) {
	let number = e.target.innerHTML;
	if(number == '<i class="bi bi-backspace-fill"></i>' || e.target.classList.contains('bi-backspace-fill')) {
		pinValue = pinValue.slice(0, -1);
		updatePinFields();
		return;
	}
	if(number == '<i class="bi bi-check"></i>' || e.target.classList.contains('bi-check')) {
		validatePin();
		return;
	}
	if(pinValue.length >= 4) {
		return;
	}
	pinValue += number;
	updatePinFields();
}

function updatePinFields() {
	let pin = pinValue;
	pinInput1.value = pin[0] || "";
	pinInput2.value = pin[1] || "";
	pinInput3.value = pin[2] || "";
	pinInput4.value = pin[3] || "";
}

