#!/usr/bin/python

import os
import os.path
import subprocess
import json
import codecs

code_template = """
// File autogenerated by create_boot_string.py, run configure to regenerate.
// We need to keep all json translation files inside StreamingAssets for translation
// However boot strings need to be included as a part of BootStrap.scene.
// Since meta file guids can change when created if we just copied, instead
// we include these strings as code.
using System.Collections.Generic;
namespace Anki.Cozmo.Generated {{
  public class LocBootStrings {{
    private static Dictionary<string, string> _EnBootStrings = new Dictionary<string, string> {{
{en}
    }};
    private static Dictionary<string, string> _DeBootStrings = new Dictionary<string, string> {{
{de}
    }};
    private static Dictionary<string, string> _FrBootStrings = new Dictionary<string, string> {{
{fr}
    }};
    private static Dictionary<string, string> _JaBootStrings = new Dictionary<string, string> {{
{ja}
    }};
    public static string GetBootString(string key, UnityEngine.SystemLanguage lang) {{
      switch (lang) {{
      case UnityEngine.SystemLanguage.German:
        if (_DeBootStrings.ContainsKey(key)) {{
          return _DeBootStrings[key];
        }}
        break;
      case UnityEngine.SystemLanguage.French:
        if (_FrBootStrings.ContainsKey(key)) {{
          return _FrBootStrings[key];
        }}
        break;
      case UnityEngine.SystemLanguage.Japanese:
        if (_JaBootStrings.ContainsKey(key)) {{
          return _JaBootStrings[key];
        }}
        break;
      }}
      if (_EnBootStrings.ContainsKey(key)) {{
        return _EnBootStrings[key];
      }}
      return key;
    }}
  }}
}}"""


def create_boot_strings_code_file(game_root):
    # These are special boot strings that need to be localized, but need to be pulled out of asset bundles and loaded
    localized_strings_dir_src = os.path.join(game_root, 'unity', 'Cozmo', 'Assets', 'StreamingAssets', 'LocalizedStrings')
    localized_strings_dir_dest = os.path.join(game_root, 'unity', 'Cozmo', 'Assets', 'Scripts', 'Generated')
    localized_bootstrings_code_filepath = os.path.join(localized_strings_dir_dest, 'LocBootStrings.cs')
    # always update if it didn't exist already
    old_file_exists = os.path.exists(localized_bootstrings_code_filepath)
    files_updated = not old_file_exists
    all_locale_strings = {}
    if not os.path.exists(localized_strings_dir_dest):
        os.makedirs(localized_strings_dir_dest)
    for localeName in os.listdir(localized_strings_dir_src):
        if os.path.isdir(os.path.join(localized_strings_dir_src, localeName)):
            single_locale_src = os.path.join(localized_strings_dir_src, localeName, 'BootStrings.json')
            #if any src file was updated we rewrite the generated file
            if not files_updated:
                files_updated = os.stat(single_locale_src).st_mtime - os.stat(localized_bootstrings_code_filepath).st_mtime > 1
            locale_strings = ""
            with open(single_locale_src) as data_file:
                data = json.load(data_file)
                for k in data:
                    if "translation" in data[k]:
                        locale_strings += "                   { \"" + k + "\", \"" + data[k]["translation"] + "\"},\n"
                all_locale_strings[localeName[:2]] = str(locale_strings)

    if files_updated:
        with codecs.open(localized_bootstrings_code_filepath, 'w+', 'utf-8') as fo:
            #clear previous write
            fo.seek(0)
            fo.truncate()
            code_template_encoded = str(code_template)
            fo.write(str(code_template_encoded.format(**all_locale_strings)))

if __name__ == '__main__':
    project_root = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip("\r\n")
    create_boot_strings_code_file(project_root)
