import * as ActivityPub from "./ActivityPub.js";

let LoginButton = document.getElementsByClassName("Login")[0];
let LogoutButton = document.getElementsByClassName("Logout")[0];
let Origin = window.location.origin + "/HTML/mail"

LoginButton.onclick = (event) => {
	HandleAuthentication();
}

LogoutButton.onclick = (event) => {
	console.log("Does nothing so far.");
}

async function HandleAuthentication() {
	let InstanceData = await fetch("https://wetdry.world/api/v1/apps?client_name=Channel Viewer&redirect_uris=" + Origin + "&scopes=" + ActivityPub.Scopes, {method: "POST"})
	.then((response) => response.json());
	// Save the client stuff as cookies (STRICTLY THIS SITE!).
	document.cookie = "client_id=" + InstanceData.client_id + ";samesite=strict;path=/;expires=Thu, 01 Jan 9999 00:00:00 GMT;";
	document.cookie = "client_secret=" + InstanceData.client_secret + ";samesite=strict;path=/;expires=Thu, 01 Jan 9999 00:00:00 GMT;";
	// Now authenticate the app.
	let InstanceInfo = await fetch("https://wetdry.world/api/v1/instance", {method: "GET"})
	.then((response) => response.json());
	document.location.href = "https://wetdry.world/oauth/authorize?client_id=" + InstanceData.client_id + "&redirect_uri=" + Origin + "&response_type=code&scope=" + ActivityPub.Scopes;
}

// When the website starts, check to see if you actually went and got a code.
async function HandleLogin() {
	if (document.location.href.split("code=").length > 1 && document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=") > 1) {
		let code = document.location.href.split("code=")[1];
		let ClientID = document.cookie.split("; ").find((row) => row.startsWith("client_id="))?.split("=")[1];
		let ClientSecret = document.cookie.split("; ").find((row) => row.startsWith("client_secret="))?.split("=")[1];
		
		let AuthenticationToken = await fetch("https://wetdry.world/oauth/token?client_id=" + ClientID + "&client_secret=" + ClientSecret + "&redirect_uri=" + Origin + "&grant_type=authorization_code&code=" + code, {method: "POST"})
		.then((response) => response.json());
		// Cookify These
		document.cookie = "access_token=" + AuthenticationToken.access_token + ";samesite=strict;path=/;expires=Thu, 01 Jan 9999 00:00:00 GMT;";
		document.cookie = "token_type=" + AuthenticationToken.token_type + ";samesite=strict;path=/;expires=Thu, 01 Jan 9999 00:00:00 GMT;";
	}
}

function CheckLogin() {
	// Check for a token.
	if (document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=").length > 1) {
		// Swap the buttons
		LoginButton.remove();
		LogoutButton.setAttribute("style", "");
	}
}

// Below is the thing it populates if you login.
async function PopulateFavorites() {
	// Check for a token.
	if (document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=").length > 1) {
		// Get the varaibles that are stored in cookies.
		let AccessToken = document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=")[1];
		let TokenType = document.cookie.split("; ").find((row) => row.startsWith("token_type="))?.split("=")[1];
		let Favorites = await fetch("https://wetdry.world/api/v1/favourites", {method: "GET", headers: {"Authorization": TokenType + " " + AccessToken}})
		.then((response) => response.json());
		let FavoritesArea = document.getElementsByClassName("Favorites")[0];
		// Populate the favorites area.
		for (let i in Favorites) {
			FavoritesArea.innerHTML += "<article style='top:" + getRandomArbitrary(0, 84) + "%; left: " + getRandomArbitrary(0, 84) + "%;'  class='Favorite'></article>";
			FavoritesArea.getElementsByClassName("Favorite")[i].innerHTML = Favorites[i].content;
		}
	}
}

async function PopulateBookmarks() {
	// Check for a token.
	if (document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=").length > 1) {
		// Get the varaibles that are stored in cookies.
		let AccessToken = document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=")[1];
		let TokenType = document.cookie.split("; ").find((row) => row.startsWith("token_type="))?.split("=")[1];
		let Bookmarks = await fetch("https://wetdry.world/api/v1/bookmarks", {method: "GET", headers: {"Authorization": TokenType + " " + AccessToken}})
		.then((response) => response.json());
		let BookmarksArea = document.getElementsByClassName("Bookmarks")[0];
		// Populate the Bookmarks area.
		for (let i in Bookmarks) {
			BookmarksArea.innerHTML += "<article style='top:" + getRandomArbitrary(0, 84) + "%; left: " + getRandomArbitrary(0, 84) + "%;' class='Bookmark'></article>";
			BookmarksArea.getElementsByClassName("Bookmark")[i].innerHTML = Bookmarks[i].content;
		}
	}
}

async function PopulateNotifications() {
	// Check for a token.
	if (document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=").length > 1) {
		// Get the varaibles that are stored in cookies.
		let AccessToken = document.cookie.split("; ").find((row) => row.startsWith("access_token="))?.split("=")[1];
		let TokenType = document.cookie.split("; ").find((row) => row.startsWith("token_type="))?.split("=")[1];
		let Notifications = await fetch("https://wetdry.world/api/v1/notifications", {method: "GET", headers: {"Authorization": TokenType + " " + AccessToken}})
		.then((response) => response.json());
		console.log(Notifications);
		let NotificationsArea = document.getElementsByClassName("Notifications")[0];
		// Populate the Conversations area.
		for (let i in Notifications) {
			NotificationsArea.innerHTML += "<article style='top:" + getRandomArbitrary(0, 84) + "%; left: " + getRandomArbitrary(0, 84) + "%;' class='Notification'></article>";
			NotificationsArea.getElementsByClassName("Notification")[i].innerHTML = Notifications[i].status.content;
		}
	}
}

// Runs on website start.
// Remove traces of "login".
CheckLogin();

// Authentication.
HandleLogin();

// Populate the areas.
PopulateFavorites();
PopulateBookmarks();
PopulateNotifications();

// Functions stolen elsewhere
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}
