#!/usr/bin/env python3

from __future__ import unicode_literals, print_function
import json
import subprocess
import os
import codecs


def strip_obj_c(string):
    return string.rstrip("\"\n").lstrip("@\"")


def add_obj_c(string):
    return '@\"'+string+'\"'


def convert_to_json(file):
    enDict = {}
    desciptionDict = {}
    keys = []
    for line in file:
        if '#define EN_' in line:
            lineSplitArray = line.split(' ', 2)
            enDict[lineSplitArray[1]] = [strip_obj_c(lineSplitArray[2])]
        if 'NSLocalizedString' in line:
            commaSplit = line.split(',', 1)
            description = strip_obj_c(commaSplit[1].rstrip(')\n').lstrip(' '))
            parSplit = commaSplit[0].split('(', 1)
            key = parSplit[1].strip()
            desciptionDict[key] = description
        if 'OTRLanguageManager' in line:
            keys.append(line.split(' ')[1])

            pass

    combiniedDict = {}
    for key in enDict:
        newKey = key[3:]
        if newKey not in keys:
            print("error, not in keys" + newKey)
        else:
            combiniedDict[newKey] = {'string': enDict[key][0], 'comment': desciptionDict[key]}
    newFile = codecs.open('strings.json', 'w', 'utf-8')
    newFile.write(json.dumps(combiniedDict, sort_keys=True, indent=4))
    newFile.close()


def gen_doc_string(string, comment):
    doc_string = '/** "' + string + '", ' + comment + ' */\n'
    return doc_string


def gen_h_line(key):
    h_line = 'FOUNDATION_EXPORT NSString* ' + key + '();\n'
    return h_line


def gen_m_function(key, return_value):
    m_line = 'NSString* ' + key + '() { return ' + return_value + '; }\n'
    return m_line


def gen_m_line(key, string):
    return_value = '[OTRLanguageManager translatedString:' + add_obj_c(string) + ']'
    m_line = gen_m_function(key=key, return_value=return_value)
    return m_line


def gen_nslocalized_line(string, comment):
    temp_line = 'NSLocalizedString('+add_obj_c(string)+','+add_obj_c(comment)+')\n'
    return temp_line


def json_to_strings(strings_dict, strings_h_path, strings_m_path, temp_strings_h_path):
    strings_h_file = codecs.open(strings_h_path, 'w', 'utf-8')
    strings_m_file = codecs.open(strings_m_path, 'w', 'utf-8')
    tempStrings = codecs.open(temp_strings_h_path, 'w', 'utf-8')

    strings_h_file.write('// DO NOT EDIT THIS FILE. EDIT strings.json then run python StringsConverter.py\n\n')
    strings_h_file.write('@import Foundation;\nNS_ASSUME_NONNULL_BEGIN\n')

    strings_m_file.write('// DO NOT EDIT THIS FILE. EDIT strings.json then run python StringsConverter.py\n\n')
    strings_m_file.write('#import "OTRStrings.h"\n#import "OTRLanguageManager_Private.h"\n')

    for key, value in sorted(strings_dict.items()):
        string = value['string']
        comment = value['comment']

        doc_string = gen_doc_string(string=string, comment=comment)
        h_line = gen_h_line(key=key)
        m_line = gen_m_line(key=key, string=string)

        strings_h_file.write(doc_string + h_line)
        strings_m_file.write(doc_string + m_line)

        nslocalized_line = gen_nslocalized_line(string=string, comment=comment)
        tempStrings.write(nslocalized_line)

    # Special case for .h file where always display the 'Default' in iOS system language
    default_string = 'Default'
    default_comment = 'default string to revert to normal language behaviour'
    default_key = 'DEFAULT_LANGUAGE_STRING'
    default_h_line = gen_h_line(default_key)
    default_docstring = gen_doc_string(string=default_string, comment=default_comment)
    nslocalized_line = gen_nslocalized_line(string=default_string, comment=default_comment)
    default_m_line = gen_m_function(key=default_key, return_value=nslocalized_line)

    strings_h_file.write(default_docstring + default_h_line)
    strings_m_file.write(default_docstring + default_m_line)

    tempStrings.write(nslocalized_line)

    strings_h_file.write('NS_ASSUME_NONNULL_END\n')
    strings_h_file.close()
    strings_m_file.close()
    tempStrings.close()


def genStrings(inputFilePath, outputDirectoryPath):
    subprocess.call(['genstrings', '-o', outputDirectoryPath, inputFilePath])


def main():
    script_directory = os.path.dirname(os.path.abspath(__file__))
    strings_json_path = os.path.join(script_directory, 'strings.json')
    strings_h_path = os.path.join(script_directory, 'OTRStrings.h')
    strings_m_path = os.path.join(script_directory, 'OTRStrings.m')
    temp_strings_h_path = os.path.join(script_directory, 'tempStrings.h')
    project_root_path = os.path.join(os.path.join(script_directory, os.pardir), os.pardir)
    localizations_path = os.path.join(os.path.join(project_root_path, 'OTRResources'), 'Localizations')
    base_lproj_path = os.path.join(localizations_path, 'Base.lproj')

    # Compare Modification Dates
    strings_json_modified = os.path.getmtime(strings_json_path)
    strings_h_modified = os.path.getmtime(strings_h_path)
    strings_m_modified = os.path.getmtime(strings_m_path)

    # Bail out if strings.json hasn't been modified recently
    if (strings_json_modified < strings_h_modified) and (strings_json_modified < strings_m_modified):
        print('No changes to strings.json detected.')
        return

    strings_json_file = codecs.open(strings_json_path, 'r', 'utf-8')
    strings_dict = json.load(strings_json_file)
    json_to_strings(strings_dict, strings_h_path, strings_m_path, temp_strings_h_path)
    strings_json_file.close()

    genStrings(inputFilePath=temp_strings_h_path, outputDirectoryPath=base_lproj_path)
    os.remove(temp_strings_h_path)


if __name__ == "__main__":
    main()
