/*
 * Moviepilot list exporter
 * e.g. https://www.moviepilot.de/liste/listname-username
 *
 * 1. Open your list to export in the browser
 * 2. Open the Console in the browsers DevTools
 * 3. Copy and paste this script in the console and run it
 */

const movies = [['Title', 'Year', 'German title']];
const promises = [];
const titleRequest = async (movieLink) => {
    const response = await fetch(movieLink);
    const html = await response.text();
    const originalTitle = html.match(/"original_title":"([^"]+)",/);

    return originalTitle[1] || '';
};

document.querySelectorAll('#list_items .board_item').forEach((movie) => {
    const movieLink = movie.querySelector('.board_content h3 a');
    const germanTitle = movieLink.innerHTML;
    let year = '';
    const yearText = movie.querySelector('.board_content h3 span').innerHTML;

    if (yearText) {
        year = yearText.match(/([0-9]{4})/g)[0];
    }

    promise = titleRequest(movieLink).then((title) => {
        movies.push([title, year, germanTitle]);
    });

    promises.push(promise);
});

Promise.all(promises).then(() => {
    let csvContent = movies.map((movie) => movie.map((movieData) => `"${movieData}"`).join(',')).join('\n');

    const download = (content, fileName, mimeType) => {
        const link = document.createElement('a');
        mimeType = mimeType || 'application/octet-stream';

        link.href = URL.createObjectURL(
            new Blob([content], {
                type: mimeType,
            })
        );
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const listTitle = document
        .querySelector('h1')
        .childNodes[0].textContent.replace(/(\r\n|\n|\r)/gm, '')
        .replace(/[/\\?%*:|"<>]/g, '');
    download(csvContent, `${listTitle}.csv`, 'text/csv;encoding:utf-8');
});