if (document.location.search.includes('dark-theme=true')) {
    document.body.classList.add('dark-theme');
}

const load = () => {
    const l0 = document.createElement('div')
    const l1 = document.createElement('div')
    const l2 = document.createElement('div')
    l0.classList.add('lds-ripple')

    l0.appendChild(l1)
    l0.appendChild(l2)
    return l0
}

let charts = [];

const createButton = (title, libraries, methods) => {
    const button = document.createElement('button')
    button.textContent = title;
    button.onclick = async () => {
        document.getElementById('pip-graph').innerHTML = ''
        document.getElementById('star-graph').innerHTML = ''
        const e = load()
        document.body.appendChild(e)
        const selectedLibraries = libraries.filter(e => document.querySelector(`#${e}Checkbox`).checked);
        if (charts.length !== 0) {
            for (const chart of charts) {
                chart.destroy()
            }
        }
        for (const method of methods()) {
            charts.push(await method(selectedLibraries))
        }
        document.body.removeChild(e)
    };

    return button;
}

const initialize = async () => {
    const inferResponse = await fetch(`initialize`);
    const inferJson = await inferResponse.json();
    const graphsDiv = document.getElementsByClassName('graphs')[0];
    const librarySelector = document.getElementById('library-selector');
    const graphSelector = document.getElementById('graph-selector');

    const introSpan = document.createElement("h3")
    introSpan.textContent = "Select libraries to display"
    librarySelector.appendChild(introSpan);

    const graphSpan = document.createElement("h3")
    graphSpan.textContent = "Select graphs to display"
    graphSelector.appendChild(graphSpan);

    for (const element of inferJson) {
        const div = document.createElement('div');
        const checkBox = document.createElement('input');
        checkBox.type = 'checkbox'
        checkBox.id = `${element}Checkbox`;

        const checkBoxLabel = document.createElement('label');
        checkBoxLabel.textContent = element.charAt(0).toUpperCase() + element.slice(1)

        checkBoxLabel.appendChild(checkBox)
        div.appendChild(checkBoxLabel)

        librarySelector.appendChild(div)
    }

    for (const element of ['pip', 'stars']) {
        const div = document.createElement('div');
        const checkBox = document.createElement('input');
        checkBox.type = 'checkbox'
        checkBox.id = `${element}CheckboxGraph`;

        const checkBoxLabel = document.createElement('label');
        checkBoxLabel.textContent = element.charAt(0).toUpperCase() + element.slice(1)

        checkBoxLabel.appendChild(checkBox)
        div.appendChild(checkBoxLabel)

        graphSelector.appendChild(div)
    }

    const fetchButton = createButton('Fetch', inferJson, () => {
        const graphNames = ['pip', 'stars'].filter(e => document.querySelector(`#${e}CheckboxGraph`).checked);
        const graphs = []

        if (graphNames.includes('pip'))
            graphs.push(retrievePipInstalls)

        if (graphNames.includes('stars'))
            graphs.push(retrieveStars)

        return graphs
    })
    graphsDiv.appendChild(fetchButton);
};

const retrievePipInstalls = async (libraryNames) => {
    const inferResponse = await fetch(`retrievePipInstalls?input=${libraryNames}`);
    const inferJson = await inferResponse.json();
    const colors = ['Lilac', 'Red', 'Blue', 'Orange', 'Green']

    console.log(inferJson)
    const labels = Array.from(inferJson['day']).map(e => new Date(e))
    const datasets = [];
    for (const element in inferJson) {
        if (element === 'day')
            continue

        const color = colors.pop()
        datasets.push({
            label: element,
            data: inferJson[element],
            backgroundColor: color,
            borderColor: color,
            tension: 0.01,
            pointRadius: 1,
            borderWidth: 2,
            fill: false
        })
    }

    const ctx = document.getElementById('pip-graph');

    const myChart = new Chart(ctx, {
        type: 'line',
        data: {labels, datasets},
        options: {
            scales: {
                y: {
                    beginAtZero: true
                },
                x: {
                    type: 'time',
                }
            },
        }
    });
    return myChart;
};

const retrieveStars = async (libraryNames) => {
    const inferResponse = await fetch(`retrieveStars?input=${libraryNames}`);
    const inferJson = await inferResponse.json();
    const colors = ['Lilac', 'Red', 'Blue', 'Orange', 'Green']

    const labels = Array.from(inferJson['day']).map(e => new Date(e))
    const datasets = [];
    for (const element in inferJson) {
        if (element === 'day')
            continue

        const color = colors.pop()
        datasets.push({
            label: element,
            data: inferJson[element],
            backgroundColor: color,
            borderColor: color,
            tension: 0.01,
            pointRadius: 1,
            borderWidth: 2,
            fill: false
        })
    }

    const ctx = document.getElementById('star-graph');

    const myChart = new Chart(ctx, {
        type: 'line',
        data: {labels, datasets},
        options: {
            scales: {
                y: {
                    beginAtZero: true
                },
                x: {
                    type: 'time',
                }
            },
        }
    });
    return myChart;
};

(
    async () => {
        const e = load()
        document.body.appendChild(e)
        await initialize()
        document.body.removeChild(e)
    }
)();