#!/usr/bin/env python

import gettext, os, sys

from optparse import OptionParser

class PropertiesIterator:
    def __init__(self, fname):
        self.stream = open (fname, 'rb')

    def __iter__(self):
        return self

    def next(self):
        name = None
        value = None
        extending = True
        while extending:
            line = self.stream.readline()
            if line == '':
                self.stream.close()
                raise StopIteration()

            line = line.strip()
            if not line or line[0] == '#':
                continue

            extending = line[-1] == '\\'
            if extending:
                line = line[0:-1]

            if not name:
                name = line.split('=', 1)[0]
                value = line[len(name) + 1:]
            else:
                value += line

        return (name, value);

class NoopTranslations:
    def gettext(self, s):
        return s
    

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("-d", "--debug", dest="debug", action="store_true",
                      help="enable debugging output",
                      default=False)

    parser.add_option("-i", "--input", dest="input",
                      help="path to input file (default: %default)",
                      default="dragonfly.properties")

    parser.add_option("-l", "--lingua", dest="lingua",
                      help="lingua to generate")

    parser.add_option("-o", "--output", dest="output",
                      help="path to output file (default: [lingua].js)")

    parser.add_option("-p", "--podir", dest="podir",
                      help="path to directory with po files (default: %default)",
                      default="../../../po")

    (options, args) = parser.parse_args()

    if not options.lingua:
        print "You must specify a language."
        sys.exit(1)

    potfile = "%s/%s.gmo" % (options.podir, options.lingua)
    if options.lingua != 'en':
        t = gettext.GNUTranslations(open(potfile, 'rb'))

    if not options.output:
        options.output = "%s.js" % options.lingua

    tmpfile = options.output + ".tmp"

    tmpf = open (tmpfile, 'wb')
    tmpf.write ("{");

    if options.debug:
        print "{",
        fmt = "%s\n\t\"%s\": \"%s\""
    else:
        fmt = "%s\"%s\":\"%s\""

    comma = ""
    for (name, value) in PropertiesIterator(options.input):

        if options.lingua != 'en':
            value = t.gettext(name)
        
        s = fmt % (comma, name, value)
        comma = ","
        
        if options.debug:
            print s,

        tmpf.write (s)

    if options.debug:
        print "\n}"
        tmpf.write ("\n")
    tmpf.write("}")

    os.rename (tmpfile, options.output)
