const puppeteer = require('puppeteer-core')

const formatString = str => str.replace(/[^A-Za-z0-9]/g, '+').toLowerCase()

const scrape = async search => {
    
    const browser = await puppeteer.launch({
        "headless":true,
        executablePath: '/usr/bin/chromium',
        args:['--disable-notifications', '--no-sandbox']
    })
    const page = await browser.newPage()
    await page.goto(`https://www.primevideo.com/search/ref=atv_nb_sr?phrase=${formatString(search)}&ie=UTF8&language=fr_FR`)

    const anchorSelector = '#av-search > div > div.X8aBJ_.av-search-grid.av-s-g-clear > div:nth-child(1) > div > div._38SAO3.tst-hover-container > div._1y15Fl.dvui-beardContainer.D0Lu_p.av-grid-beard > div._1Opa2_.dvui-packshot.av-grid-packshot > a'
    const spanSelector = anchorSelector + ' > span'
    const imageSelector = anchorSelector + ' > img'

    const resultName = await page.$eval(imageSelector, (el) => el.alt)

    // check if there is no result
    if (formatString(search) != formatString(resultName)) {
        await browser.close()
        return {platform:'prime', movie:search, available:false}
    }

    try {
        const primeLogo = await page.$eval(spanSelector, (el) => el.className)
        await browser.close()
        return {platform:'prime', movie:search, available:true}
    } catch (err) {
        await browser.close()
        return {platform:'prime', movie:search, available:false}
    }   
}

module.exports = {
    scrape:scrape
}
