// 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",
//	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35",
//	"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35",
//	"Mozilla/5.0 (Windows NT 6.1; rv:109.0) Gecko/20100101 Firefox/113.0",
//	"Mozilla/5.0 (Android 12; Mobile; rv:109.0) Gecko/113.0 Firefox/113.0",
//	"mozilla/5.0 (macintosh; intel mac os x 10.15; rv:109.0) gecko/20100101 firefox/113.0",
];

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

function makeRequest() {
    var username = document.getElementById('username').value;
    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) {
        // Process the URLs in the archives array
        if (data && data.archives && Array.isArray(data.archives)) {
            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');

                    // Use the concatenatedPgn variable as needed
                    console.log("Concatenated PGN:", concatenatedPgn);
                })
                .catch(function(error) {
                    console.error("Error in one or more requests:", error);
                });
        }

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

    document.head.appendChild(script);
}

function makeAsyncRequest(url, userAgent) {
    return new Promise(function (resolve, reject) {
        // Generate a unique callback function name
        const callbackName = `jsonpCallback_${Date.now()}_${Math.floor(Math.random() * 1000)}`;

        // Create a script element
        const script = document.createElement('script');

        // Define the callback function
        window[callbackName] = function (data) {
            // Clean up the script and the callback function
            document.head.removeChild(script);
            delete window[callbackName];

            // Resolve the promise with the response data
            resolve(data);
        };

        // Construct the URL with the callback parameter
        const callbackUrl = `${url}?callback=${callbackName}&user_agent=${encodeURIComponent(userAgent)}`;
        script.src = callbackUrl;

        // Append the script element to the document
        document.head.appendChild(script);

        // Handle errors
        script.onerror = function (error) {
            // Clean up the script and the callback function
            document.head.removeChild(script);
            delete window[callbackName];

            // Reject the promise with the error
            reject(error);
        };
    });
}
