const LineReader = require('n-readlines');
const zipdir = require('zip-dir');
const copydir = require('copy-dir');
const commander = require('commander');
const del = require('del');
const file = require('./src/file');
const deploy = require('./deploy.json');

// Lecture des arguments
commander.version('1.2.1');
commander
    .option('-z, --zip', 'create a zip file for each programs', false)
    .option('-c, --compress', 'zip and deletes the non-zip version of programs', false);
commander.parse(process.argv);
const zip = commander.zip || commander.compress;
const remove = commander.compress;


// Constante
const OUT = './dist/';

// Creation dossier destination
file.makedir(OUT);

// Séparation de chaque programme
deploy.programs.forEach(program => {
    // Création du dossier
    const distPath = OUT + program.name;
    file.makedir(distPath);
    // Creation dossier data
    file.makedir(distPath + '/data');
    file.put(distPath + '/data/.gitkeep', '');
    // Copie des fichiers commun
    file.makedir(distPath + '/src');
    file.list('./src').forEach(f => {
        if (!file.isDir('./src/' + f)) {
            file.copy('./src/' + f, distPath + '/src/' + f);
        }
    });
    // Copie dossier propre à chaque programme
    copydir.sync('./src/' + program.name, distPath + '/src/' + program.name, {
        utimes: true,
        mode: true,
        cover: true
    });
    // Copie fichier main
    file.copy(program.main, distPath + '/main.js');
    // Copie package.json
    const pckg = require('./package.json');
    pckg.scripts = program.scripts;
    pckg.version = program.version;
    program.rm_dependencies.forEach(elt => {
        delete pckg.dependencies[elt];
    });
    let json = JSON.stringify(pckg, null, 4);
    json = json.replace(new RegExp(program.main, 'g'), 'main.js');
    file.put(distPath + '/package.json', json);
    // Ecriture ReadMe
    file.put(distPath + '/README.md', readMe(program.part).replace(new RegExp(program.main, 'g'), 'main.js'));
    // Zip du code pour distribution
    if (zip) {
        //zipdir.zipFolder(distPath, distPath + '.zip', err => {});

        zipdir(distPath, {saveTo: distPath + '.zip'}, (err, buffer) => {
            if (err) {
                console.error('Error when zipping files', err);
            } else {
                console.info(`Zip file created for ${program.name} in ${distPath}.zip`);
                // Si besoins on supprime les versions non zipper des dossier
                if (remove) {
                    del(distPath + '/**').then(deletedPaths => {
                        file.fs.rmdir(distPath, () => {
                            console.info(`Directory ${distPath} deleted`);
                        });
                    });
                }
            }
        });
    }
    // Message de fin
    console.info(`${program.name} deployed in ${distPath}`);
});

// Fonction découpage readme
function readMe(part) {
    const liner = new LineReader('./README.md');
    let data = '';
    let line = liner.next().toString();
    while (line !== 'false' && line.indexOf('## Partie ') === -1) {
        data += '\n' + line;
        line = liner.next().toString();
    }
    while (line !== 'false' && line.indexOf('## Partie ' + part) === -1) {
        line = liner.next().toString();
    }
    data += '\n' + line;
    line = liner.next().toString();
    while (line !== 'false' && line.indexOf('## Partie ') === -1) {
        data += '\n' + line;
        line = liner.next().toString();
    }
    if (line !== 'false') {
        liner.close();
    }
    return data;
}
