'use strict';

const { get, geta, ctxa, ed } = require('../utils/q');
const slugify = require('../utils/slugify');

function scrapeAll(scenes, site) {
    return scenes.map(({ q, qa, qu, qd, ql, qi, qt }) => {
        const url = qu('.text-thumb a');
        const { pathname } = new URL(url);
        const channelUrl = qu('.badge');

        if (site?.parameters?.extract && q('.badge', true) !== site.name) {
            return null;
        }

        const release = {};

        release.url = channelUrl ? `${channelUrl}${pathname}` : url;
        release.entryId = pathname.match(/\/\d+/)[0].slice(1);
        release.title = q('.text-thumb a', true);

        release.date = qd('.date', 'YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/);
        release.duration = ql('.date', /(\d{2}:)?\d{2}:\d{2}/);

        release.actors = qa('.category a', true);

        release.poster = qi('img.video_placeholder, .video-images img');
        release.teaser = { src: qt() };

        return release;
    }).filter(Boolean);
}

function scrapeScene({ q, qd, qa }, url, _site, baseRelease) {
    const release = { url };

    const { pathname } = new URL(url);
    release.entryId = pathname.match(/\/\d+/)[0].slice(1);

    release.title = q('.trailer-block_title', true);
    release.description = q('.info-block:nth-child(3) .text', true);
    release.date = qd('.info-block_data .text', 'MMMM D, YYYY', /\w+ \d{1,2}, \d{4}/);

    const duration = baseRelease?.duration || Number(q('.info-block_data .text', true).match(/(\d+)\s+min/)?.[1]) * 60;
    if (duration) release.duration = duration;

    release.actors = qa('.info-block_data a[href*="/models"]', true);
    release.tags = qa('.info-block a[href*="/categories"]', true);

    const posterEl = q('.update_thumb');
    const poster = posterEl.getAttribute('src0_3x') || posterEl.getAttribute('src0_2x') || posterEl.dataset.src;

    if (poster && baseRelease?.poster) release.photos = [poster];
    else if (poster) release.poster = poster;

    return release;
}

function scrapeProfile({ q, qa, qtx }) {
    const profile = {};

    const keys = qa('.model-descr_line:not(.model-descr_rait) p.text span', true);
    const values = qa('.model-descr_line:not(.model-descr_rait) p.text').map(el => qtx(el));
    const bio = keys.reduce((acc, key, index) => ({ ...acc, [slugify(key, { delimiter: '_' })]: values[index] }), {});

    if (bio.height) profile.height = Number(bio.height.match(/\((\d+)cm\)/)[1]);
    if (bio.weight) profile.weight = Number(bio.weight.match(/\((\d+)kg\)/)[1]);
    if (bio.race) profile.ethnicity = bio.race;

    if (bio.date_of_birth) profile.birthdate = ed(bio.date_of_birth, 'MMMM D, YYYY');
    if (bio.birthplace) profile.birthPlace = bio.birthplace;

    if (bio.measurements) {
        const [bust, waist, hip] = bio.measurements.split('-');
        if (!/\?/.test(bust)) profile.bust = bust;
        if (!/\?/.test(waist)) profile.waist = waist;
        if (!/\?/.test(hip)) profile.hip = hip;
    }

    if (bio.hair) profile.hair = bio.hair;
    if (bio.eyes) profile.eyes = bio.eyes;

    if (/various/i.test(bio.tattoos)) profile.hasTattoos = true;
    else if (/none/i.test(bio.tattoos)) profile.hasTattoos = false;
    else if (bio.tattoos) {
        profile.hasTattoos = true;
        profile.tattoos = bio.tattoos;
    }

    if (/various/i.test(bio.piercings)) profile.hasPiercings = true;
    else if (/none/i.test(bio.piercings)) profile.hasPiercings = false;
    else if (bio.piercings) {
        profile.hasPiercings = true;
        profile.piercings = bio.piercings;
    }

    if (bio.aliases) profile.aliases = bio.aliases.split(',').map(alias => alias.trim());

    const avatar = q('.model-img img');
    profile.avatar = avatar.getAttribute('src0_3x') || avatar.getAttribute('src0_2x') || avatar.dataset.src;

    const releases = qa('.video-thumb');
    profile.releases = scrapeAll(ctxa(releases));

    return profile;
}

async function fetchLatest(site, page = 1) {
    const url = site.parameters?.extract
        ? `https://cherrypimps.com/categories/movies_${page}.html`
        : `${site.url}/categories/movies_${page}.html`;
    const qLatest = await geta(url, 'div.video-thumb');

    return qLatest && scrapeAll(qLatest, site);
}

async function fetchScene(url, site, release) {
    const qScene = await get(url);

    return qScene && scrapeScene(qScene, url, site, release);
}

async function fetchProfile(actorName, scraperSlug) {
    const actorSlug = slugify(actorName);
    const actorSlug2 = slugify(actorName, { delimiter: '' });

    const [url, url2] = ['cherrypimps', 'wildoncam'].includes(scraperSlug)
        ? [`https://${scraperSlug}.com/models/${actorSlug}.html`, `https://${scraperSlug}.com/models/${actorSlug2}.html`]
        : [`https://${scraperSlug.replace('xxx', '')}.xxx/models/${actorSlug}.html`, `https://${scraperSlug.replace('xxx', '')}.xxx/models/${actorSlug2}.html`];

    const qActor = await get(url) || await get(url2);

    return qActor && scrapeProfile(qActor);
}

module.exports = {
    fetchLatest,
    fetchScene,
    fetchProfile,
};
