// Image Handler
const baseUrl = 'https://api.unsplash.com/photos/random?client_id=[KEY]&orientation=landscape&topics=nature';
const apiKey = 'tYOt7Jo94U7dunVcP5gt-kDKDMjWFOGQNsHuhLDLV8k'; // Take from config
const fullUrl = baseUrl.replace('[KEY]', apiKey);

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') {
		fetch('https://staging.thegreydiamond.de/projects/photoPortfolio/api/getRand.php?uuid=01919dec-b2cd-7adc-8ca2-a071d1169cbc&unsplash=true&orientation=landscape')
			.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 = `Photo by <a href="${data.user.links.html}" target="_blank">${data.user.name}</a> on <a href="https://unsplash.com" target="_blank">Unsplash</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();