// Image Handler
const showModeImage = '/static/media/showModeLockscreen.jpg';

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

let currentImageHandle;

document.body.addEventListener('click', () => {
	window.location.href = '/user_select';
});

// Lock screen or show mode
let screenState = 'lock';

let cookieScreen = getCookie('screen');
if (cookieScreen) {
	screenState = cookieScreen;
}

function handleImage() {
	if (screenState === 'lock') {
		const apiParams = {
			// default galery; spring awakens
			uuid: '01919dec-b2cd-7adc-8ca2-a071d1169cbc;01953de0-3aa7-71f1-bfff-cbf9488efa64',
			unsplash: true,
			orientation: 'landscape',
			height: window.screen.availHeight,
			width: window.screen.availWidth,
			cropCenteringMode: 'sm'
		};

		const apiUrl = `https://staging.thegreydiamond.de/projects/photoPortfolio/api/getRand.php?${new URLSearchParams(apiParams).toString()}`;

		fetch(apiUrl)
			.then((response) => response.json())
			.then((data) => {
				// data = {
				// 	urls: {
				// 		regular: "https://imageproxy.thegreydiamond.de/ra5iqxlyve6HpjNvC1tzG50a14oIOgiWP95CxIvbBC8/sm:1/kcr:1/aHR0cHM6Ly9zdGFn/aW5nLnRoZWdyZXlk/aWFtb25kLmRlL3By/b2plY3RzL3Bob3Rv/UG9ydGZvbGlvL2Rl/bW9IaVJlcy9QMTE5/MDgzMC1zY2hpbGQu/anBn.webp"
				// 	},
				// 	user: {
				// 		name: "Sören Oesterwind",
				// 		links: {
				// 			html: "https://thegreydiamond.de"
				// 		}
				// 	}
				// }
				if (!currentImageHandle) {
					// Create a page filling div which contains the image
					currentImageHandle = document.createElement('div');
					currentImageHandle.style.position = 'absolute';
					currentImageHandle.style.top = '0';
					currentImageHandle.style.left = '0';
					currentImageHandle.style.width = '100%';
					currentImageHandle.style.height = '100%';
					currentImageHandle.style.backgroundImage = `url(${data.urls.regular})`;
					currentImageHandle.style.backgroundSize = 'cover';
					currentImageHandle.style.opacity = 1;
				} else {
					// Create a new div behind the current one and delete the old one when the new one is loaded
					let newImageHandle = document.createElement('div');
					newImageHandle.style.position = 'absolute';
					newImageHandle.style.top = '0';
					newImageHandle.style.left = '0';
					newImageHandle.style.width = '100%';
					newImageHandle.style.height = '100%';
					newImageHandle.style.backgroundImage = `url(${data.urls.regular})`;
					newImageHandle.style.backgroundSize = 'cover';
					newImageHandle.style.opacity = 1;
					newImageHandle.style.transition = '1s';
					newImageHandle.style.zIndex = 19999;
					document.body.appendChild(newImageHandle);

					currentImageHandle.style.opacity = 0;
					setTimeout(() => {
						currentImageHandle.remove();
						newImageHandle.style.zIndex = 200000;
						currentImageHandle = newImageHandle;
					}, 1000);

					// Set the credits
					credits.innerHTML = `"${data.title}" by <a href="${data.user.links.html}" class="external-link" target="_blank">${data.user.name}</a>`;
					credits.style.zIndex = 300000;
				}
			})
			.catch((error) => {
				console.error('Error fetching image: ', error);
			});
	} else {
		if (currentImageHandle) {
			// Check if the image is already loaded
			if (currentImageHandle.style.backgroundImage === `url("${showModeImage}")`) {
				return;
			}
			// Create a new div behind the current one and delete the old one when the new one is loaded
			let newImageHandle = document.createElement('div');
			newImageHandle.style.position = 'absolute';
			newImageHandle.style.top = '0';
			newImageHandle.style.left = '0';
			newImageHandle.style.width = '100%';
			newImageHandle.style.height = '100%';
			newImageHandle.style.backgroundImage = `url(${showModeImage})`;
			newImageHandle.style.backgroundSize = 'cover';
			newImageHandle.style.opacity = 1;
			newImageHandle.style.transition = '1s';
			document.body.appendChild(newImageHandle);

			setTimeout(() => {
				currentImageHandle.remove();
				currentImageHandle = newImageHandle;
			}, 1000);
		}
	}
}

function handleTimeAndDate() {
	let time = new Date();
	let hours = time.getHours();
	let minutes = time.getMinutes();
	let day = time.getDate();
	let month = time.getMonth();
	month += 1;
	let year = time.getFullYear();

	let timeHandle = document.getElementById('time');
	let dateHandle = document.getElementById('date');

	timeHandle.innerHTML = `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds()}`;
	// Datum in format Montag, 22.12.2024
	dateHandle.innerHTML = `${getDay(time.getDay())}, ${day < 10 ? '0' + day : day}.${month < 10 ? '0' + month : month}.${year}`;
}

function getDay(day) {
	return ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'][day];
}

// Set the image handler to run every 10 minutes
setInterval(handleImage, 60 * 1000 * 10);
handleImage();
handleImage();

// Set the time and date handler to run every minute
setInterval(handleTimeAndDate, 500);
handleTimeAndDate();
