#!/usr/bin/env node

function fatal(message, code) {
    console.log((filename || "html2po") + ": " + message);
    process.exit(code || 1);
}

function usage() {
    console.log("usage: po2json [--module=template.js] input output");
    process.exit(2);
}

var fs, po2json, Jed, stdio;

try {
    fs = require('fs');
    po2json = require('po2json');
    Jed = require('jed');
    stdio = require('stdio');
} catch(ex) {
    fatal(ex.message, 127); /* missing looks for this */
}

var argi = 2;
var filename = null;

var opts = stdio.getopt({
    module: { key: "m", args: 1, description: "Module template to include" },
    output: { key: "o", args: 1, description: "Output file" },
});

if (opts.args.length != 1) {
    usage();
}

parse();

function prepareHeader(header) {
    var body, statement, plurals = header["plural-forms"], ret = null;
    if (plurals) {
        try {
            /* Check that the plural forms isn't being sneaky since we build a function here */
            Jed.PF.parse(plurals);
        } catch(ex) {
            fatal("bad plural forms: " + ex.message, 1);
        }

        /* A function for the front end */
	statement = header["plural-forms"];
        if (statement[statement.length - 1] != ';')
            statement += ';';
	ret = 'function(n) {\nvar nplurals, plural;\n' + statement + '\nreturn plural;\n}';

        /* Added back in later */
        delete header["plural-forms"];
    }

    /* We don't need to be transferring this */
    delete header["project-id-version"];
    delete header["report-msgid-bugs-to"];
    delete header["pot-creation-date"];
    delete header["po-revision-date"];
    delete header["last-translator"];
    delete header["language-team"];
    delete header["mime-version"];
    delete header["content-type"];
    delete header["content-transfer-encoding"];

    return ret;
}

/* Parse and process the po data */
function parse() {
    filename = opts.args[0];
    po2json.parseFile(opts.args[0], { "fuzzy": true }, function(err, jsonData) {
        var plurals, pos;

        if (err)
            fatal(err.message);

        var header = jsonData[""];
        if (header)
            plurals = prepareHeader(header);

        var data = JSON.stringify(jsonData, null, 1);

        /* We know the brace in is the location to insert our function */
        if (plurals) {
            pos = data.indexOf('{', 1);
            data = data.substr(0, pos + 1) + "'plural-forms':" + String(plurals) + "," + data.substr(pos + 1);
        }

        if (data == JSON.stringify({}))
            finish("");
        else
            wrap(data);
    });
}

/* Wrap the data if desired */
function wrap(data) {
    if (opts.module) {
        filename = opts.module;
        fs.readFile(opts.module, { encoding: "utf-8" }, function(err, template) {
            if (err)
                fatal(err.message);
            data = template.replace('{"":{"language":"en"}}', data);
            finish(data);
        });
    } else {
        finish(data);
    }
}

/* Write it out */
function finish(data) {
    if (opts.output) {
        fs.writeFile(opts.output, data, function(err) {
            if (err)
	        fatal(err.message);
            process.exit(0);
        });
    } else {
        process.stdout.write(data);
        process.exit(0);
    }
}
