<commit_before>/* Copyright(c) 2018 <NAME>. */
/* Copyright(c) 2016 <NAME>. */

/* jshint strict: true, esversion: 6 */

'use strict';

import util from './util';
import request_scheduler from './request_scheduler';
import azad_order from './order';
import azad_table from './table';

let scheduler = null;
let background_port = null;
let years = null;
let stats_timeout = null;

function getScheduler() {
    if (!scheduler) {
        resetScheduler();
    }
    return scheduler;
}

function getBackgroundPort() {
    return background_port;
}

function setStatsTimeout() {
    const sendStatsMsg = () => {
        getBackgroundPort().postMessage({
            action: 'statistics_update',
            statistics: getScheduler().statistics(),
            years: years,
        });
    }
    clearTimeout(stats_timeout);
    stats_timeout = setTimeout(
        () => {
            setStatsTimeout();
            sendStatsMsg();
        },
        2000
    ); 
}

function resetScheduler() {
    if (scheduler) {
        scheduler.abort();
    }
    scheduler = request_scheduler.create();
    setStatsTimeout();
}

function getYears() {
    if(typeof(getYears.years) === 'undefined') {
        console.log('getYears() needs to do something');
        const snapshot = util.findMultipleNodeValues(
            '//select[@name="orderFilter"]/option[@value]',
            document.documentElement
        );
        getYears.years = snapshot.map(
            elem => elem.textContent
                        .replace('en', '')  // amazon.fr
                        .replace('nel', '')  // amazon.it
                        .trim()
        )
        .filter( element => (/^\d+$/).test(element) )
        .filter( year => (year >= '2004') );
    }
    console.log('getYears() returning ', getYears.years);
    return getYears.years;
}

function fetchAndShowOrders(years) {
    resetScheduler();
    azad_order.getOrdersByYear(
        years,
        getScheduler(),
        getYears()[0]
    ).then(
        orderPromises => {
            let beautiful = true;
            if (orderPromises.length >= 500) {
                beautiful = false;
                alert('500 or more orders found. That\'s a lot! We\'ll start you off with a plain table to make display faster. You can click the blue "datatable" button to restore sorting, filtering etc.');
            }
            azad_table.displayOrders(orderPromises, beautiful);
            return document.querySelector('[id="order_table"]');
        }
    );
}

function advertiseYears() {
    const years = getYears();
    console.log('advertising years', years);
    getBackgroundPort().postMessage({
        action: 'advertise_years',
        years: years
    });
}

function registerContentScript() {
    background_port = chrome.runtime.connect(null, {name: 'azad_inject'});
    getBackgroundPort().onMessage.addListener( msg => {
        switch(msg.action) {
            case 'dump_order_detail':
                azad_table.dumpOrderDiagnostics(msg.order_detail_url)<commit_msg>pull years from all amazon site pages, not just order pages<commit_after>/* Copyright(c) 2018 <NAME>. */
/* Copyright(c) 2016 <NAME>. */

/* jshint strict: true, esversion: 6 */

'use strict';

import util from './util';
import request_scheduler from './request_scheduler';
import azad_order from './order';
import azad_table from './table';

let scheduler = null;
let background_port = null;
let years = null;
let stats_timeout = null;

const SITE = window.location.href.match( /\/\/([^/]*)/ )[1];

function getScheduler() {
    if (!scheduler) {
        resetScheduler();
    }
    return scheduler;
}

function getBackgroundPort() {
    return background_port;
}

function setStatsTimeout() {
    const sendStatsMsg = () => {
        getBackgroundPort().postMessage({
            action: 'statistics_update',
            statistics: getScheduler().statistics(),
            years: years,
        });
    }
    clearTimeout(stats_timeout);
    stats_timeout = setTimeout(
        () => {
            setStatsTimeout();
            sendStatsMsg();
        },
        2000
    ); 
}

function resetScheduler() {
    if (scheduler) {
        scheduler.abort();
    }
    scheduler = request_scheduler.create();
    setStatsTimeout();
}

function getYears() {
    const getPromise = function() {
        const url = 'https://' + SITE + '/gp/css/order-history?ie=UTF8&ref_=nav_youraccount_orders';
        return fetch(url).then( response => response.text() )
                         .then( text => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(
                text, 'text/html'
            );
            const snapshot = util.findMultipleNodeValues(
                '//select[@name="orderFilter"]/option[@value]',
                doc.documentElement
            );
            const years = snapshot.map(
                elem => elem.textContent
                            .replace('en', '')  // amazon.fr
                            .replace('nel', '')  // amazon.it
                            .trim()
            ).filter( element => (/^\d+$/).test(element) )
             .filter( year => (year >= '2004') );
            return years;
        });
    }
    if(typeof(getYears.years) === 'undefined') {
        console.log('getYears() needs to do something');
        getYears.years = getPromise();
    }
    console.log('getYears() returning ', getYears.years);
    return getYears.years;
}

function fetchAndShowOrders(years) {
    resetScheduler();
    getYears().then(
        all_years => azad_order.getOrdersByYear(
            years,
            getScheduler(),
            all_years[0]
        )
    ).then(
        orderPromises => {
            let beautiful = true;
            if (orderPromises.length >= 500) {
                beautiful = false;
                alert('500 or more orders found. That\'s a lot! We\'ll start you off with a plain table to make display faster. You can click the blue "datatable" button to restore sorting, filtering etc.');
            }
            azad_table.displayOrders(orderPromises, beautiful);
            return document.querySelector('[id="order_table"]');
        }
    );
}

function advertiseYears() {
    getYears().then( years => {
        console.log('advertising years', years);
        getBackgroundPort().postMessage({
            action: 'advertise_years',
            years: years
        });
    });
}

function registerContentScript() {
    background_port = chrome.runtime.connect(null, {name: 'azad_inject'});
    getBackgroundPort().onMessage.addListener( msg => {
        switch(msg.action) {
            case 'dump_order_detail':
                azad_table.dumpOrderDiagnostics(msg.order_detail_url)
{'fraction_non_alphanumeric': 0.1317737636955878, 'fraction_numerical': 0.007403020432336393, 'mean_word_length': 2.15359477124183, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 29, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6226678', 'n_tokens_mistral': 1952, 'n_tokens_neox': 1876, 'n_words': 424}