import * as MastodonAPI from "./MastodonAPI.js";
import * as BlueskyAPI from "./BlueskyAPI.js";
import * as TumblrAPI from "./TumblrAPI.js";
import * as Variables from "./Variables.js";

// GLOBAL VARS
// fuck you. I see why website developers use divs so fucking often.
let Warning = document.getElementsByClassName("WarningMessage")[0];
let Main = document.getElementsByClassName("MainBefore")[0];
let ContainerContainer = document.getElementsByClassName("PostContainerContainer")[0];
let ClickableContainers = ContainerContainer.getElementsByClassName("PostContainer")[2].children;

let BrowserWidth = window.innerWidth;
let BrowserHeight = window.innerHeight;

let ArrowsButton = document.getElementsByClassName("Arrow");
let SettingButton = document.getElementsByClassName("Setting")[0];
let MailButton = document.getElementsByClassName("Mail")[0];
let PostingButton = document.getElementsByClassName("Posting")[0];

// Sounds
const ButtonSound = new Audio("Audio/button-305770.mp3");
const WarningClick = new Audio("Audio/button-pressed-38129.mp3");
const BackgroundMusic = new Audio("Audio/soft-piano-music-312509.mp3");

// Update a timer
function UpdateTime() {
	let TimeNow = new Date();
	let Hour = TimeNow.getHours();
	let Minute = TimeNow.getMinutes();
	
	var WebsiteTime = document.getElementsByClassName("Time")[0]
	WebsiteTime.innerHTML = "";
	if (Hour < 10) {
		WebsiteTime.innerHTML = WebsiteTime.innerHTML + "0" + Hour;
	} else {
		WebsiteTime.innerHTML = WebsiteTime.innerHTML + Hour;
	}
	WebsiteTime.innerHTML = WebsiteTime.innerHTML + ":";
	if (Minute < 10) {
		WebsiteTime.innerHTML = WebsiteTime.innerHTML + "0" + Minute;
	} else {
		WebsiteTime.innerHTML = WebsiteTime.innerHTML + Minute;
	}
}

setInterval(UpdateTime, 1000);

// When the window is resized
onresize = (event) => {
	BrowserWidth = window.innerWidth;
	BrowserHeight = window.innerHeight;
	window.dispatchEvent(new Event("load"));
}

// When the window finally reloads
onload = (event) => {
	Warning.setAttribute("style", "height: " + BrowserHeight + "px; width: " + BrowserWidth + "px;");
	Main.setAttribute("style", "height: " + BrowserHeight + "px; width: " + BrowserWidth + "px;");
	ArrowsButton[1].setAttribute("style", "left: " + (BrowserWidth - 100) + "px;");
}

// On clicking the warning message
Warning.onclick = (event) => {
	Warning.classList.add("WarningFadeOutAnimation");
	// fixes a damn stupid bug
	document.getElementsByClassName("BlinkAnimation")[0].classList.remove("BlinkAnimation");
	Main.classList.add("MainFadeInAnimation");
	Main.classList.remove("MainBefore");
	WarningClick.play();
	setTimeout(() => {
		Main.classList.remove("MainFadeInAnimation");
		Main.classList.add("MainAfter");
		BackgroundMusic.play();
	}, 5000);
	Main = document.getElementsByClassName("MainFadeInAnimation")[0];
	PosterContainerUpdate();
}

// Clicking the next button
ArrowsButton[1].onclick = (event) => {
	if (!ContainerContainer.classList.contains("NextAnimation")) {
		ContainerContainer.classList.add("NextAnimation");
		ButtonSound.play();
		setTimeout(() => {
			ContainerContainer.classList.remove("NextAnimation");
		}, 1000);
		PosterContainerUpdate("Forward");
	}
}

// Clicking the back button
ArrowsButton[0].onclick = (event) => {
	if (!ContainerContainer.classList.contains("BackAnimation")) {
		ContainerContainer.classList.add("BackAnimation");
		ButtonSound.play();
		setTimeout(() => {
			ContainerContainer.classList.remove("BackAnimation");
		}, 1000);
		PosterContainerUpdate("Backward");
	}
}

for (let i of ClickableContainers) {
	i.onclick = (event) => {
		let content = i.getElementsByClassName("PostContent")[0].innerHTML
		let username = i.getElementsByClassName("Username")[0].innerHTML
		// Save some info
		window.location.href = "./HTML/expanded.html?username=" + username + "&content=" + content;
	}
}

// These numbers are here so you don't go back.
let MastodonLoadedFeed = [];
let BlueskyLoadedFeed = [];
let CurrentThing = 0;

// Call this to update the things :)
async function PosterContainerUpdate(Direction) {
	let Lim = 6;
	let Website = localStorage.getItem(Variables.MastodonWebsite);
	
	let Mastodon = true;
	
	// Mastodon gaining of timeline.
	if (localStorage.getItem(Variables.MastodonWebsite) == null) {
		// The default website is Wetdry :3
		console.log("No Mastodon instance. multiplying mastodon posts by 2...");
		Lim = Lim * 2;
		Mastodon = false;
	} else if (MastodonLoadedFeed == 0) {
		MastodonLoadedFeed = await MastodonAPI.GetTimeline("");
	}
	// Bluesky gaining of timeline.
	if (localStorage.getItem(Variables.BlueskyPDS) == null) {
		console.log("No Bluesky instance. multiplying mastodon posts by 2...");
		Lim = Lim * 2;
	} else if (BlueskyLoadedFeed.length == 0) {
		BlueskyLoadedFeed = await BlueskyAPI.GetTimeline("").then((response) => response.feed);
	}
	if (Direction == "Forward") {
		CurrentThing = CurrentThing + Lim;
	} else if (Direction == "Backward") {
		if (CurrentThing - Lim >= 0) {
			CurrentThing = CurrentThing - Lim;
		}
	}
	// Debugging
	console.log(MastodonLoadedFeed);
	console.log(BlueskyLoadedFeed);
	// The first one is for counting.
	// The countergroup increments to another timeline once posts hit the "limit".
	let counter = 0;
	let countergroup = 0;
	if (Mastodon == false) {
		countergroup = countergroup + 1;
	}
	// This var is meant to stop "already seen" posts.
	let BlueskyPostsDup = [];
	for (let i of ClickableContainers) {
		switch(countergroup) {
			// Mastodon
			case 0:
				if (MastodonLoadedFeed[CurrentThing + counter] == undefined) {
					let TempFeed = await MastodonAPI.GetTimeline(MastodonLoadedFeed[CurrentThing + counter - 1].id);
					MastodonLoadedFeed = MastodonLoadedFeed.concat(TempFeed);
				}
				// Content warning. Don't show the content unless clicked!!!
				if (MastodonLoadedFeed[CurrentThing + counter].spoiler_text != "") {
					i.getElementsByClassName("PostContent")[0].innerHTML = "<b>WARNING: " + MastodonLoadedFeed[CurrentThing + counter].spoiler_text + "</b>";
					i.getElementsByClassName("Username")[0].innerHTML = MastodonLoadedFeed[CurrentThing + counter].account.username;
					break;
				}
				// Check for a reblog.
				if (MastodonLoadedFeed[CurrentThing + counter].reblog != null) {
					i.getElementsByClassName("PostContent")[0].innerHTML = MastodonLoadedFeed[CurrentThing + counter].reblog.content;
					i.getElementsByClassName("Username")[0].innerHTML = MastodonLoadedFeed[CurrentThing + counter].reblog.account.username + " ( R: " + MastodonLoadedFeed[CurrentThing + counter].account.username + " )";
				} else {
					i.getElementsByClassName("PostContent")[0].innerHTML = MastodonLoadedFeed[CurrentThing + counter].content;
					i.getElementsByClassName("Username")[0].innerHTML = MastodonLoadedFeed[CurrentThing + counter].account.username;
				}
				break;
			// Bsky
			case 1:
				if (BlueskyLoadedFeed[CurrentThing + counter] == undefined) {
					let TempFeed = await BlueskyAPI.GetTimeline(BlueskyLoadedFeed[CurrentThing + counter - 1].post.indexedAt).then((response) => response.feed)
					BlueskyLoadedFeed = BlueskyLoadedFeed.concat(TempFeed);
				}
				// check for "already seen" posts, then put it as a seen post.
				BlueskyLoadedFeed = CheckForDups(BlueskyLoadedFeed, BlueskyPostsDup, counter);
				BlueskyPostsDup.push(BlueskyLoadedFeed[counter].post.uri);
				// Labels
				if (BlueskyLoadedFeed[CurrentThing + counter].post.labels.length != 0) {
					i.getElementsByClassName("PostContent")[0].innerHTML = "<b>LABELS APPLIED: ";
					i.getElementsByClassName("Username")[0].innerHTML = BlueskyLoadedFeed[CurrentThing + counter].post.author.handle;
					for (let lab of BlueskyLoadedFeed[CurrentThing + counter].post.labels) {
						i.getElementsByClassName("PostContent")[0].innerHTML = i.getElementsByClassName("PostContent")[0].innerHTML + lab.val + " ";
					}
					i.getElementsByClassName("PostContent")[0].innerHTML = i.getElementsByClassName("PostContent")[0].innerHTML + "</b>";
					break;
				}
				// Check for a reblog
				if (BlueskyLoadedFeed[CurrentThing + counter].hasOwnProperty("reason") && BlueskyLoadedFeed[CurrentThing + counter].reason.$type == "app.bsky.feed.defs#reasonRepost") {
					i.getElementsByClassName("PostContent")[0].innerHTML = BlueskyLoadedFeed[CurrentThing + counter].post.record.text;
					i.getElementsByClassName("Username")[0].innerHTML = BlueskyLoadedFeed[CurrentThing + counter].post.author.handle + " ( R: " + BlueskyLoadedFeed[CurrentThing + counter].reason.by.handle + " )";
				} else {
					i.getElementsByClassName("PostContent")[0].innerHTML = BlueskyLoadedFeed[CurrentThing + counter].post.record.text;
					i.getElementsByClassName("Username")[0].innerHTML = BlueskyLoadedFeed[CurrentThing + counter].post.author.handle;
				}
				// Direction for where you go :3
				break;
		}
		counter = counter + 1;
		if (counter >= Lim) {
			counter = 0;
			countergroup = countergroup + 1;
		}
	}
}

// Assistant function to help with checking for duplicates.
function CheckForDups(Timeline, DupeArray, counter) {
	for (let j of DupeArray) {
		if (j == Timeline[counter].post.uri) {
			Timeline.splice(counter, 1);
			console.log("Culled a duplicate post.")
			Timeline = CheckForDups(Timeline, DupeArray, counter);
		}
	}
	return Timeline;
}

// Open the settings
SettingButton.onclick = (event) => {
	window.location.href = "./HTML/setting.html";
}

// Open the notifs, private message, favorites, ... anything mail related!
MailButton.onclick = (event) => {
	window.location.href = "./HTML/mail.html";
}

// Open the posting area
PostingButton.onclick = (event) => {
	window.location.href = "./HTML/post.html";
}