// mainScript.js

import userAgents from './userAgents.js';

// Declare the script variable
//
let script;

window.downloadPGN = function() {
    const username = document.getElementById('usernameInput').value;

    if (!username) {
        alert('Please enter a username.');
        return;
    }

    // Create a callback function to handle the JSONP response for archives
    const archivesCallback = 'handleArchivesResponse';
    window[archivesCallback] = function(data) {
        document.head.removeChild(script); // Remove the script element after execution
        threddGames(data); // Pass the list of archive URLs to the threaded function
    };

    // Fetch player archives using JSONP
    playerArchives(username, archivesCallback);
};

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

function playerArchives(username, callback) {
    const apiKey = 'YOUR_API_KEY'; // Replace with your Chess.com API key
    const url = `https://api.chess.com/pub/player/${username}/games/archives?apikey=${apiKey}`;

    // Choose a random user agent from the userAgents array
    const user_agent = getRandomUserAgent();

    // Create a script element
    const script = document.createElement('script');
    script.id = 'jsonpScript';
    script.src = `${url}&callback=${callback}`;
    
    // Add the User-Agent header to the script element
    script.setAttribute('User-Agent', user_agent);

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

async function playerMonthly(url, callback) {
    const user_agent = getRandomUserAgent();
    const headers = {
        'User-Agent': user_agent,
    };

    const response = await fetch(url + '/pgn', { headers });
    const games = await response.text();
    window[callback](games); // Execute the callback function with the PGN data
}

async function threddGames(archiveURLs) {
    const gamesList = [];

    // Using Promise.all to wait for all threads to complete
    await Promise.all(archiveURLs.map(async (url) => {
        return new Promise(async (resolve) => {
            const monthlyGamesCallback = 'handleMonthlyGamesResponse';
            window[monthlyGamesCallback] = function(data) {
                handleDownload(data, gamesList, resolve);
            };

            // Fetch monthly games using JSONP
            await playerMonthly(url, monthlyGamesCallback);
        });
    }));

    // Combine and save the games to a file
    const pgnDb = gamesList.join('\n\n');
    const username = document.getElementById('usernameInput').value;
    createDownloadLink(pgnDb, `${username}.pgn`);
}

function handleDownload(data, gamesList, resolve) {
    gamesList.push(data);
    resolve(); // Resolve the promise to indicate completion of this thread
}

function createDownloadLink(data, filename) {
    const blob = new Blob([data], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');
    a.href = url;
    a.download = filename;

    document.body.appendChild(a);
    a.click();

    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}
