#!/usr/bin/env python
"""
This file is part of Industrial Stations Renewal (ISR).
ISR is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
ISR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ISR. If not, see <http://www.gnu.org/licenses/>.
"""

"""
===============
lang_nml2nfo.py
===============

Converts an NML language file to NFO language files.

Requires 3 arguments:
    Filename of NML language file to be converted
    Filename of template file used for the conversion
    Filename of output NFO language file

Coded by mart3p, 'properly' coded by Alberth
"""

import codecs # used for reading/writing files - more unicode friendly than standard open() module
import sys
import os
import re
import argparse

def parse_lang(lang_filename):
    """
    Build a dictionary from an NML language file. Returns the dictionary.

    Based on code from the 'FISH ship set' by andythenorth.
    FISH is licensed under GPL v2.
    """

    lang_file = codecs.open(lang_filename, 'r','utf8')
    strings = {}
    for line in lang_file:
        # process the language id
        if line.startswith("##grflangid"):
            lang_id = int(line[11:], 16)
            # make English the default language
            if lang_id == 1: lang_id = 0x7f
            strings["{LANG_ID}"] = "%02X" % (lang_id,)
            strings["{LANG_ID_80}"] = "%02X" % (lang_id + 0x80,)

        i = line.find(":")
        if i > 0:
            name = "{" + line[:i].strip() + "}"
            text = '"' + line[i+1:].rstrip() + '"'
            strings[name] = text

    lang_file.close()
    return strings


def multiple_replace(strings, text):
    """
    Replace in 'text' all occurrences of any key in the given
    dictionary by its corresponding value. Returns the new string.

    Based on code from:
    http://code.activestate.com/recipes/81330-single-pass-multiple-replace/
    """

    # create a regular expression from the dictionary keys
    regex = re.compile("(%s)" % "|".join(re.escape(k) for k in strings.keys()))
    # for each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: strings[mo.group()], text)


def run(nml_lang_filename, template_filename, nfo_out_filename):
    currentdir = os.curdir

    action14_flag = os.path.basename(template_filename).startswith('action14_')

    # make a dictionary from NML language file
    lang_dict = parse_lang(os.path.join(currentdir, nml_lang_filename))

    # open the template file and use dictionary to replace strings
    lines_nfo = []
    no_desc = False

    template_file = codecs.open(os.path.join(currentdir, template_filename), 'r','utf8')
    for line in template_file:
        line = multiple_replace(lang_dict, line)
        if action14_flag:
            if 'STR_GRF_DESCRIPTION' in line: no_desc = True
        lines_nfo.append(line)
    template_file.close()

    # process the NFO
    text_nfo_out = []

    if action14_flag:
        for idx, line in enumerate(lines_nfo):
            # insert colour code
            if ('ISR)' in line): line = line.replace('ISR)','ISR)" 98 "')
            # strip untranslated lines
            # if description is missing remove lines 2 to 5
            if not (no_desc and idx >= 2 and idx <= 5) and 'STR_PARAM_' not in line:
                text_nfo_out.append(line)
    else:
        for line in lines_nfo:
            # strip untranslated lines
            if 'STR_NAME_' not in line and 'STR_CLASS_NAME_' not in line:
                text_nfo_out.append(line)

    # write to NFO output file
    nfo_file = codecs.open(os.path.join(currentdir, nfo_out_filename), 'w','utf8')
    nfo_file.write("".join(text_nfo_out))
    nfo_file.close()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description= "Convert an NML language file to an NFO language file.")
    parser.add_argument('nml_lang_file', help="name of the NML input file")
    parser.add_argument('template_file', help="name of the template file")
    parser.add_argument('nfo_out_file', help="name of the NFO output file")
    args = parser.parse_args()

    nml_lang_filename = args.nml_lang_file
    template_filename = args.template_file
    nfo_out_filename = args.nfo_out_file

    if not os.path.exists(nml_lang_filename):
        sys.exit("[PYTHON] lang_nml2nfo.py: error: file " + nml_lang_filename + " not found")
    elif not os.path.exists(template_filename):
        sys.exit("[PYTHON] lang_nml2nfo.py: error: file " + template_filename + " not found")
    else:
        run(nml_lang_filename, template_filename, nfo_out_filename)
