#! /usr/bin/env python3
# Produce a spreadsheet for entry of translated phrases
# Reads base.pot and creates a spreadsheet for all languages (with blank values) in _LANGUAGE_CODES


import sys
import argparse
import json

_LANGUAGE_CODES = {
    'ENGLISH':    'en',
    'FRENCH':     'fr',
    'GERMAN':     'de',
    'DUTCH':      'nl',
    'NORWEGIAN':  'no',
    'SWEDISH':    'sv',
    'DANISH':     'da',
    'SPANISH':    'es',
    'PORTUGUESE': 'pt',
    'ITALIAN':    'it',
    'POLISH':     'pl',
    'FINNISH':    'fi',
    'RUSSIAN':    'ru',
}

class GenerateSpreadsheet:
    def __init__(self, base_file, spreadsheet_file):
        self._base_file = base_file
        self._spreadsheet_file = spreadsheet_file

    # Read and concatenate strings between msgid and msgstr
    def read_phrase(self, f):
        results = None
        while results == None:
            line = f.readline()
            if len(line) == 0:
                results = False
            else:
                line = line.strip()
                if line[0:5] == "msgid":
                    results = eval(line[5:])
                    while line[0:6] != "msgstr":
                        line = f.readline()
                        if len(line) != 0:
                            line = line.strip()
                            if line[0:6] != "msgstr":
                                results += eval(line) 

                            
        return results


    def run(self):
        with open(self._base_file, "r") as base:
            with open(self._spreadsheet_file, "w") as output:
                # Write header
                output.write("\t".join(list(_LANGUAGE_CODES)))
                output.write("\n")
                phrase = None
                while phrase != False:
                    phrase = self.read_phrase(base)
                    # print("Phrase: %s" % phrase)
                    if phrase != False and len(phrase) != 0:
                        output.write("%s%s\n" % (repr(phrase), '\t'*(len(_LANGUAGE_CODES) - 1)))

        return 0

        

def main():
    parser = argparse.ArgumentParser(description='Rhpro translation spreadsheet generator')

    parser.add_argument("-b", "--base",
                        dest="base_file",
                        default="base.pot",
                        help="base template (default 'base.pot')")

    parser.add_argument("-f", "--csv",
                        dest="spreadsheet_file",
                        default="spreadsheet_translations.csv",
                        help="translations file (default 'spreadsheet_translations.csv')")

    args = parser.parse_args()
    
    application = GenerateSpreadsheet(args.base_file, args.spreadsheet_file)

    return application.run()

if __name__ == '__main__':
    sys.exit(main())
