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

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

// Mastodon
let MastodonWebsite = "https://wetdry.world";
let MastodonClientID = "mastodon_client_id";
let MastodonClientSecret = "mastodon_client_secret";
let MastodonAccessToken = "mastodon_access_token";
let MastodonTokenType = "mastodon_access_token";

// Bluesky (TODO: use these variables).
let BlueskyApp = "https://bsky.app";
let BlueskyPDS = "https://bsky.social";

// Tumblr
let TumblrWebsite = "https://www.tumblr.com";

LoginButton.onclick = (event) => {
	MastodonAPI.HandleAuthentication(MastodonWebsite, MastodonClientID, MastodonClientSecret);
}

LogoutButton.onclick = (event) => {
	document.cookie = MastodonAccessToken + "=nothing;" + ";samesite=strict;path=/;expires=0000-01-01;";
	document.cookie = MastodonTokenType + "=nothing;" + ";samesite=strict;path=/;expires=0000-01-01;";
	console.log("Cleared the access token.");
}

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

// Below is the thing it populates if you login.
async function PopulateFavorites() {
	let Favorites = MastodonAPI.GetFavorites(MastodonWebsite, MastodonAccessToken, MastodonTokenType);
	
	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() {
	let Bookmarks = MastodonAPI.GetBookmarks(MastodonWebsite, MastodonAccessToken, MastodonTokenType);
	
	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() {
	let Notifications = MastodonAPI.GetNotifications(MastodonWebsite, MastodonAccessToken, MastodonTokenType);
	
	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();

// So far: login. TODO: Change this later.
MastodonAPI.GainToken(MastodonWebsite, MastodonClientID, MastodonClientSecret, MastodonAccessToken, MastodonTokenType);

// 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;
}

// The next section is dedicated to testing.
// WARNING: I don't know what I am doing.
BlueskyAPI.ClientDPoP();
BlueskyAPI.AssertionJWT("Nothing");

async function BlueskyTestingAuthorization() {
	let WellKnown = await BlueskyAPI.GetPDSWellKnown();
	let PAREndpoint = WellKnown.pushed_authorization_request_endpoint;
	
	let TestingState = generateToken(64);
	
	let TestingVerifier = await BlueskyAPI.CreatePKCECodeVerifier()
	let TestingChallenge = await BlueskyAPI.CreatePKCECodeChallenge(TestingVerifier);
	
	let TestingRequest = fetch(PAREndpoint + "?state=" + TestingState + "&pkceChallenge=" + TestingChallenge + "&scopes=atproto&login_hint=crowdedgames.group", {method: "POST"});
	console.log(TestingRequest);
}

BlueskyTestingAuthorization();

// Stolen from Brave
// TODO: implement my own function.
function generateToken(length) {
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var token = '';
    for(var i = 0; i < length; i++) {
        token += chars[Math.floor(Math.random() * chars.length)];
    }
    return token;
}
