'use strict';

const Table = require('cli-table');
const helpers = require('./helpers/helpers.js');
const logger = require('./logger');


module.exports = format;

const FORMATTERS = {
    'lastSeenTime': formatLastSeenTime,
    'reportMusic': formatReportMusic,
    'reportGeneral': formatReportGeneral,
    'retryConnectionMessage': formatRetryConnectionMessage
};

function format(type) {
    const formatter = FORMATTERS[type];
    if (typeof formatter === 'function') {
        let args = [].slice.call(arguments, 1);
        return formatter.apply(null, args);
    }

    logger.error('No formatter for type', type);
}

function formatReportMusic(docs) {
    if (!docs.length) {
        return 'No music tracks were found';
    }

    let table = new Table({
        head: ['Track', 'Times played']
    });

    docs.forEach(doc => {
        table.push([doc.track, doc.play_count]);
    });

    return table.toString();
}

function formatReportGeneral(doc) {
    let result = '';
    for (let k in doc) {
        if (k === '_id') continue;
        result += `${k.trim().replace(':', '')}: ${doc[k]}\n`;
    }

    return result;
}

function formatLastSeenTime(last_seen) {
    const regex = /\d{1,2}\:\d{2}\s{1}(am|pm){1}/i;
    if (regex.test(last_seen)) {
        let time = last_seen.match(regex)[0];
        time = helpers.convertTimeTo24hrs(time);
        last_seen = last_seen.replace(regex, time);
    }

    return last_seen;
}

function formatRetryConnectionMessage(retry_count, max_retry_attempts, user_id, url, timeout) {
    let message = '';
    message += `Attempt #${retry_count} (out of ${max_retry_attempts})\n`;
    message += 'Cannot scrape page.';
    message += 'Profile is either hidden, not existing or deleted\n';
    message += `Please check that USER_ID=${user_id} and URL=${url} are correct.\n`;
    message += `Retry after timeout (${timeout / 1000} seconds)`;

    return message;
}

@@ -623,521 +623,8 @@
 %0A%7D%0A%0A
-function formatReportMusic(docs) %7B%0A    if (!docs.length) %7B%0A        return 'No music tracks were found';%0A    %7D%0A%0A    let table = new Table(%7B%0A        head: %5B'Track', 'Times played'%5D%0A    %7D);%0A%0A    docs.forEach(doc =%3E %7B%0A        table.push(%5Bdoc.track, doc.play_count%5D);%0A    %7D);%0A%0A    return table.toString();%0A%7D%0A%0Afunction formatReportGeneral(doc) %7B%0A    let result = '';%0A    for (let k in doc) %7B%0A        if (k === '_id') continue;%0A        result += %60$%7Bk.trim().replace(':', '')%7D: $%7Bdoc%5Bk%5D%7D%5Cn%60;%0A    %7D%0A%0A    return result;%0A%7D%0A%0A
 func

Remove report formatters