// THIS SCRAPER DOES NOT CURRENTLY WORK AND IS NOT IN USE

const BASE_URL = `${process.env.REACT_APP_CORS_PROXY_URL}https://database.gdriveplayer.us`;
const MOVIE_URL = `${process.env.REACT_APP_CORS_PROXY_URL}https://database.gdriveplayer.us/player.php`;
const SHOW_URL = `${process.env.REACT_APP_CORS_PROXY_URL}https://series.databasegdriveplayer.co/player.php`;

async function findContent(searchTerm, type) {
    try {
        if (type !== 'movie') return;

        const term = searchTerm.toLowerCase()
        const tmdbRes = await fetch(`${process.env.REACT_APP_CORS_PROXY_URL}https://www.themoviedb.org/search?query=${term}`).then(d => d.text());

        const doc = new DOMParser().parseFromString(tmdbRes, 'text/html');
        const nodes = Array.from(doc.querySelectorAll('div.results > div > div.wrapper'));
        const results = nodes.slice(0, 10).map((node) => {
            let type = node.querySelector('div.details > div.wrapper > div.title > div > a').getAttribute('data-media-type');
            switch (type) {
                case 'movie':
                    type = 'movie';
                    break;
                case 'tv':
                    type = 'show';
                    // eslint-disable-next-line array-callback-return
                    return;
                case 'collection':
                    // eslint-disable-next-line array-callback-return
                    return;
                default:
                    break;
            }

            return {
                type: type,
                title: node.querySelector('div.details > div.wrapper > div.title > div > a').textContent,
                year: node.querySelector('div.details > div.wrapper > div.title > span').textContent.trim().split(' ')[2],
                slug: node.querySelector('div.details > div.wrapper > div.title > div > a').href.split('/')[4],
                source: 'gdriveplayer'
            }
        });

        if (results.length > 1) {
            return { options: results };
        } else {
            return { options: [ results[0] ] }
        }
    } catch (err) {
        console.error(err);
        throw new Error(err)
    }
}

async function getStreamUrl(slug, type, season, episode) {
    if (type !== 'movie') return;

    // const tmdbRes = await fetch(`${process.env.REACT_APP_CORS_PROXY_URL}https://www.themoviedb.org/search?query=${term}`).then(d => d.text());

    console.log(`${MOVIE_URL}?tmdb=${slug}`)
    const res = await fetch(`${MOVIE_URL}?tmdb=${slug}`).then(d => d.text());

    const embed = Array.from(new DOMParser().parseFromString(res, 'text/html').querySelectorAll('.list-server-items a'))
        .find((e) => e.textContent.includes("Mirror"))

    if (embed && embed.getAttribute('href')) {
        let href = embed.getAttribute('href');
        if (href.startsWith('//')) href = `https:${href}`;

        const res1 = await fetch(`${process.env.REACT_APP_CORS_PROXY_URL}${href}`.replace('streaming.php', 'download')).then(d => d.text());
        const sb = Array.from(new DOMParser().parseFromString(res1, 'text/html').querySelectorAll('a'))
            .find((a) => a.textContent.includes("StreamSB"));

        console.log(sb);

        if (sb && sb.getAttribute('href')) {
            console.log(sb.getAttribute('href'))
            const src = await sbPlayGetLink(sb.getAttribute('href'));
            if (src) return { url: src };
        }
    }

    return { url: '' }
}

async function sbPlayGetLink(href) {
    if (href.startsWith("//")) href = `https:${href}`;

    const res = await fetch(`${process.env.REACT_APP_CORS_PROXY_URL}${href}`).then(d => d.text());
    const a = new DOMParser().parseFromString(res, 'text/html').querySelector('table tbody tr a');

    if (a && a.getAttribute('onclick')) {
        let match = a.getAttribute("onclick").match(/'([^']+)'/gm);
        console.log(a.getAttribute("onclick"));

        if (match) {
            let [code, mode, hash] = match;

            const url = `https://sbplay2.com/dl?op=download_orig&id=${code.replace(/'/gm, "")}&mode=${mode.replace(/'/gm, "")}&hash=${hash.replace(/'/gm, "")}`;
            
            // https://sbplay2.com/dl?op=download_orig&id=glr78kyk21kd&mode=n&hash=1890245-0-0-1640889479-95e144cdfdbe0e9104a67b8e3eee0c2d
            // https://sbplay2.com/dl?op=download_orig&id=0hh6mxf5qqn0&mode=h&hash=2473604-78-149-1640889782-797bc207a16b2934c21ea6fdb1e97352
            // https://proxy-1.movie-web.workers.dev/?destination=https://sbplay2.com/dl?op=download_orig&id=glr78kyk21kd&mode=n&hash=1890245-0-0-1640889479-95e144cdfdbe0e9104a67b8e3eee0c2d

            const text = await fetch(url).then((e) => e.text());
            const a = new DOMParser().parseFromString(text, 'text/html').querySelector(".contentbox span a");
            if (a && a.getAttribute("href")) return a.getAttribute("href");
        }
    }
}

const gdriveplayer = { findContent, getStreamUrl }
export default gdriveplayer;