'use strict';

/* eslint-disable newline-per-chained-call */
const bhttp = require('bhttp');
const cheerio = require('cheerio');
const moment = require('moment');

const { matchTags } = require('../tags');

const defaultTags = {
    blacked: ['bbc'],
    blackedraw: ['bbc'],
    tushy: ['anal'],
    tushyraw: ['anal'],
    vixen: [],
    deeper: [],
};

function scrapeLatest(html, site) {
    const $ = cheerio.load(html, { normalizeWhitespace: true });

    const stateScript = $('script:contains("INITIAL_STATE")').html();
    const { videos: scenes } = JSON.parse(stateScript.slice(stateScript.indexOf('{'), stateScript.indexOf('};') + 1));

    return scenes.map((scene) => {
        const entryId = String(scene.newId);

        const {
            title,
            models: actors,
        } = scene;

        const url = `${site.url}${scene.targetUrl}`;
        const date = moment.utc(scene.releaseDateFormatted, 'MMMM DD, YYYY').toDate();
        const stars = Number(scene.textRating) / 2;

        // largest thumbnail. poster is the same image but bigger, too large for storage space efficiency
        const poster = scene.images.listing.slice(-1)[0].src;
        const trailer = scene.previews.listing.slice(-1)[0];

        return {
            url,
            entryId,
            title,
            actors,
            date,
            poster,
            trailer: {
                src: trailer.src,
                type: trailer.type,
                quality: trailer.height,
            },
            rating: {
                stars,
            },
            site,
        };
    });
}

async function scrapeScene(html, url, site) {
    const $ = cheerio.load(html, { normalizeWhitespace: true });

    const stateObject = $('script:contains("INITIAL_STATE")');
    const data = JSON.parse(stateObject.html().trim().slice(27, -1));

    const pageData = data.page.data[data.location.pathname].data;
    const entryId = pageData.video;
    const scene = data.videos.find(video => video.newId === entryId);

    const poster = scene.rotatingThumbsUrlSizes[0]['1040w'];
    const photos = pageData.pictureset.map(photo => photo.main[0].src);
    const trailer = scene.previews.listing.find(preview => preview.height === 353) || null;

    const {
        title,
        description,
        models: actors,
        totalRateVal: stars,
        runLength: duration,
        directorNames: director,
        tags: rawTags,
    } = scene;

    const date = new Date(scene.releaseDate);
    const tags = await matchTags([...defaultTags[site.slug], ...rawTags]);

    return {
        url,
        entryId,
        title,
        description,
        actors,
        director,
        date,
        duration,
        tags,
        photos,
        poster,
        trailer: trailer && {
            src: trailer.src,
            type: trailer.type,
            quality: 353,
        },
        rating: {
            stars,
        },
        site,
    };
}

async function fetchLatest(site, page = 1) {
    const url = `${site.url}/videos?page=${page}&size=7`;
    const res = await bhttp.get(url);

    if (res.statusCode === 200) {
        return scrapeLatest(res.body.toString(), site);
    }

    throw new Error(`Vixen response not OK for latest: ${res.statusCode}`);
}

async function fetchScene(url, site) {
    const res = await bhttp.get(url);

    if (res.statusCode === 200) {
        return scrapeScene(res.body.toString(), url, site);
    }

    throw new Error(`Vixen response not OK for scene (${url}): ${res.statusCode}`);
}

module.exports = {
    fetchLatest,
    fetchScene,
};
