#!/usr/bin/env node

// Imports
const program = require('commander');
const inquirer = require('inquirer');
const file = require('./src/file');
const cst = require('./src/constant');
const timer = require('./src/timer');

// Variables configs et globales
const sourceFile = './data/dblp.xml';
const outputFile = './data/extract.xml';
let verbose = false;

// Parametrage CLI
program.version('1.1.0');

program
    .option('-n, --name <string>', 'author\'s name for data extraction')
    .option('-f, --file <source>', 'path to the DBLP database in XML format', sourceFile)
    .option('-o, --output <source>', 'path for the XML file to be generated', outputFile)
    .option('-v, --verbose', 'displays more information', verbose);

// Parse des arguments CLI
program.parse(process.argv);
const name = (program.name && typeof program.name === 'string') ? program.name : null;
let source = program.file;
let out = program.output;
verbose = program.verbose;

// Verification que le fichier du pre-traitement existe
if (!file.exist(source)) {
    // Impossible de trouver le fichier XML à traiter
    console.error(cst.toString(cst.FILE_NOT_FOUND) + ': ' + source);
    process.exit(cst.FILE_NOT_FOUND);
}

// En cas d'absence de nom on le demande
if (name === null) {
    inquirer.prompt({
        type: 'input',
        name: 'name',
        message: 'Enter the name of the author whose information you want to extract: >',
    }).then(answer => {
        // Lancement du prgramme
        extract(source, answer.name);
    });
}
// Sinon on lance le programme
else {
    extract(source, name);
}

function extract(source, name) {
    name = name.trim();
    if (verbose) {
        console.info(`Extraction of ${name}'s information...`);
        timer.start();
    }
    const parser = require('./src/extract/parser').get();
    parser.from(source).search(name).parse(data => {
        if (verbose) {
            timer.stop();
            console.info(`Information about ${name} extracted in ${timer.time()}`);
        }
        // Transforme en XML et ecrit dans le fichier
        const xml = require('./src/extract/formatter').toXml(name, data);
        file.put(out, xml, true);
        // Affiche un message de fin
        console.info(`Data extracted to ${out}`);
    });
}
