#!/usr/bin/env node
'use strict';

var nopt = require('nopt');
var path = require('path');
var version = require('../package.json').version;

var knownOptions = {
    'list': Boolean,
    'extract': Boolean,
    'path': path
};

var shortcuts = {
    'x': ['--extract'],
    'l': ['--list'],
    'p': ['--path'],
    'v': ['--version']
};

var parsedOptions = nopt(knownOptions, shortcuts);

var pad = function (string, length) {
    string = String(string);

    if (length <= string.length) {
        return string;
    }

    return string + (new Array(length - string.length).join(' '));
};

var octal = function (number, digits) {
    var result = '';
    for (var i = 0; i < digits; i++) {
        result = (number & 0x07) + result;
        number >>= 3;
    }
    return result;
};

var DecompressZip = require('../lib/decompress-zip');
var zip = new DecompressZip(parsedOptions.argv.remain[0]);

zip.on('file', function (file) {
    console.log([octal(file.mode, 4), pad(file.type, 12), pad(file.compressedSize, 10), pad(file.uncompressedSize, 10), file.path].join(' '));
});

zip.on('list', function (fileList) {
    //  console.log(fileList);
});

zip.on('extract', function (result) {
    console.log(result);
});

zip.on('error', function (error) {
    console.error(error.message, error.stack);
});

if (parsedOptions.version) {
    console.log('version ' + version);
} else if (parsedOptions.list) {
    console.log('Mode Type        Zip size  Full size Path');
    console.log('---- ----        --------  --------- ----');
    zip.list();
} else if (parsedOptions.extract) {
    var options = {};

    if (parsedOptions.path) {
        options.path = parsedOptions.path;
    }

    zip.extract(options);
} else {
    console.log('Usage: decompress-zip <options> <file>');
    console.log('    -x, --extract      extract the given file');
    console.log('    -l, --list         list the contents of the given file');
    console.log('    -v, --version      extract the given file');
    console.log('    -p, --path <path>  extract the file into <path>');
    console.log('    -h, --help         show this message');
}
