'use strict';

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

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

async function getPhotos(entryId, site) {
    const { hostname } = new URL(site.url);

    const res = await bhttp.get(`https://${hostname}/gallery.php?type=highres&id=${entryId}`);
    const html = res.body.toString();

    const $ = cheerio.load(html, { normalizeWhitespace: true });
    const photos = $('a.fakethumb').map((photoIndex, photoElement) => $(photoElement).attr('data-src') || $(photoElement).attr('href')).toArray();

    return photos;
}

function scrapeLatest(html, site) {
    const $ = cheerio.load(html, { normalizeWhitespace: true });
    const sceneElements = $('.content-wrapper .scene').toArray();

    return sceneElements.map((element) => {
        const sceneLinkElement = $(element).find('h3 a');
        const thumbnailElement = $(element).find('a img');

        const url = sceneLinkElement.attr('href');
        // const title = sceneLinkElement.text();
        const entryId = url.split('/').slice(-1)[0];

        const titleText = thumbnailElement.attr('alt');
        const title = titleText.slice(titleText.indexOf(':') + 1).trim();

        const date = moment.utc($(element).find('.scene-date'), ['MM/DD/YYYY', 'YYYY-MM-DD']).toDate();

        const actors = $(element).find('.scene-models a').map((actorIndex, actorElement) => $(actorElement).text()).toArray();
        const likes = Number($(element).find('.scene-votes').text());

        const photoCount = Number(thumbnailElement.attr('thumbs_num'));
        const poster = thumbnailElement.attr('src');
        const photos = Array.from({ length: photoCount }, (val, index) => thumbnailElement.attr(`src${index + 1}`));

        const scene = {
            url,
            entryId,
            title,
            actors,
            date,
            poster,
            photos,
            rating: {
                likes,
            },
            site,
        };

        return scene;
    });
}

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

    [release.entryId] = url.split('/').slice(-1);
    release.title = $('.video-wrapper meta[itemprop="name"]').attr('content');
    release.description = $('.video-wrapper meta[itemprop="description"]').attr('content');

    release.date = moment.utc($('.video-wrapper meta[itemprop="uploadDate"]').attr('content'), 'MM/DD/YYYY').toDate();
    release.actors = $('.content-wrapper .scene-models-list a').map((actorIndex, actorElement) => $(actorElement).text()).toArray();

    const timestamp = $('.video-wrapper meta[itemprop="duration"]').attr('content');

    if (timestamp) {
        const [minutes, seconds] = timestamp.match(/\d+/g);
        release.duration = Number(minutes) * 60 + Number(seconds);
    }

    release.tags = $('.content-desc .scene-tags a').map((tagIndex, tagElement) => $(tagElement).text()).toArray();
    release.likes = Number($('.content-desc #social-actions #likes').text());

    const posterScript = $('script:contains(poster)').html();
    const posterLink = posterScript?.slice(posterScript.indexOf('https://'), posterScript.indexOf('.jpg') + 4);
    release.poster = $('meta[property="og:image"]').attr('content') || posterLink || $('#trailer_player_finished img').attr('src');

    const trailer = $('meta[property="og:video"]').attr('content') || $('#videojs-trailer source').attr('src');

    if (trailer) release.trailer = { src: trailer };

    release.photos = await getPhotos(release.entryId, site);
    release.movie = $('a[data-track="FULL MOVIE"]').attr('href');

    const siteElement = $('.content-wrapper .logos-sites a');
    if (siteElement) release.channel = slugify(siteElement.text(), { delimiter: '' });

    return release;
}

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

    const bio = qa('.model-facts li:not(.model-facts-long)', true).reduce((acc, fact) => {
        const [key, value] = fact.split(':');
        const trimmedValue = value.trim();

        if (trimmedValue.length === 0 || trimmedValue === '-') return acc;
        return { ...acc, [slugify(key, { delimiter: '_' })]: trimmedValue };
    }, {});

    const description = q('.model-facts-long', true);
    if (description) profile.description = description;

    const aliases = qtx('.aka')?.split(/,\s*/);
    if (aliases) profile.aliases = aliases;

    if (bio.birth_place) profile.birthPlace = bio.birth_place;
    if (bio.nationality) profile.nationality = bio.nationality;

    if (bio.measurements) {
        const [bust, waist, hip] = bio.measurements.split('-');

        if (bust) profile.bust = bust;
        if (waist) profile.waist = Number(waist);
        if (hip) profile.hip = Number(hip);
    }

    if (bio.weight) profile.weight = Number(bio.weight.match(/^\d+/)[0]);
    if (bio.height) profile.height = Number(bio.height.match(/^\d+/)[0]);

    if (bio.hair_color) profile.hair = bio.hair_color;
    if (bio.eye_color) profile.eye = bio.eye_color;

    if (bio.tattoos) {
        profile.hasTattoos = true;
        profile.tattoos = bio.tattoos;
    }

    if (bio.tattoos) {
        profile.hasTattoos = true;
        profile.tattoos = bio.tattoos;
    }

    if (bio.piercings) {
        profile.hasPiercings = true;
        profile.piercings = bio.piercings;
    }

    profile.avatar = q('.img-pornstar img').dataset.src;
    profile.releases = scrapeLatest(html);

    return profile;
}

async function fetchLatest(site, page = 1) {
    const { hostname } = new URL(site.url);

    if (hostname.match('private.com')) {
        const res = await bhttp.get(`${site.url}/${page}/`);

        return scrapeLatest(res.body.toString(), site);
    }

    const res = await bhttp.get(`${site.url}/scenes/${page}/`);

    return scrapeLatest(res.body.toString(), site);
}

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

    return scrapeScene(res.body.toString(), url, site);
}

async function fetchProfile(actorName) {
    const actorSearchSlug = slugify(actorName, { delimiter: '+' });
    const url = `https://www.private.com/search.php?query=${actorSearchSlug}`;
    const modelLinks = await geta(url, '.model h3 a');

    if (modelLinks) {
        const actorSlug = slugify(actorName);
        const model = modelLinks.find(({ text }) => slugify(text) === actorSlug);

        if (model) {
            const qProfile = await get(model.el.href);

            return qProfile && scrapeProfile(qProfile);
        }
    }

    return null;
}

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