// main.js

const userAgents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35",
];

function getRandomUserAgent() {
    return userAgents[Math.floor(Math.random() * userAgents.length)];
}

function makeRequest() {
    var username = document.getElementById('username').value;

    // Check if the username is blank
    if (!username.trim()) {
        alert("Please enter a username.");
        return;
    }

    var randomUserAgent = getRandomUserAgent();

    var url = `https://api.chess.com/pub/player/${username}/games/archives?callback=jsonpCallback&user_agent=${encodeURIComponent(randomUserAgent)}`;

    var script = document.createElement('script');
    script.src = url;

	window.jsonpCallback = function(data) {
		if (data && data.error && data.error.code === 0) {
			alert(`Invalid username. Please check your username and try again.`);
		} else if (data && data.archives && Array.isArray(data.archives)) {
			if (data.archives.length === 0) {
				alert(`No games found for the provided username.`);
			} else {
				const promises = data.archives.map(function(archiveUrl) {
					// Append '/.pgn' to each individual URL
					const url = archiveUrl;
					return makeAsyncRequest(url, getRandomUserAgent());
				});

				// Use Promise.all to wait for all requests to complete
				Promise.all(promises)
					.then(function(results) {
						// Concatenate the 'pgn' values
						const concatenatedPgn = results.flatMap(data => data.games.map(game => game.pgn)).join('\n');

						// Trigger download
						downloadFile(username, concatenatedPgn);
					})
					.catch(function(error) {
						console.error("Error in one or more requests:", error);
						alert("An error occurred. Please try again.");
					});
			}
		} else {
			alert("Error retrieving games data. Please check your username and try again.");
		}

		// Clean up the script element
		document.head.removeChild(script);
	};
    document.head.appendChild(script);
}

// Function to trigger download
function downloadFile(username, content) {
    const blob = new Blob([content], { type: 'text/plain' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${username}.pgn`;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(a.href);
}

// Function to make asynchronous requests
function makeAsyncRequest(url, userAgent) {
    return new Promise(function(resolve, reject) {
        const callbackName = `jsonpCallback_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
        const script = document.createElement('script');

        window[callbackName] = function(data) {
            document.head.removeChild(script);
            delete window[callbackName];
            resolve(data);
        };

        const callbackUrl = `${url}?callback=${callbackName}&user_agent=${encodeURIComponent(userAgent)}`;
        script.src = callbackUrl;

        document.head.appendChild(script);

        script.onerror = function(error) {
            document.head.removeChild(script);
            delete window[callbackName];
            reject(error);
        };
    });
}
