#!/bin/python

import os
from os.path import dirname, join, exists, relpath, splitext
import json
from json_tools import list_field_paths, field_by_path
from shutil import copy
from utils import get_answer
from bisect import insort_left
from codecs import open as copen
from sys import platform
if platform == "win32":
  from os.path import normpath as norm
  def normpath(path):
    return norm(path).replace('\\', '/')
else:
  from os.path import normpath

mod_dir = "./mod"
root_dir = "./translations"

def parseFile(filename):
  result = []
  try:
    with copen(filename, "r", 'utf-8') as f:
      result = json.load(f)
  except:
    print("Failed to parse: " + filename)
    quit(1)
  return result

def get_data(field, target_file, original_file):
  ## Returns json structure from "target_file" and
  ## index of a field in this structure related to "field" in "original_file"
  ## original_file - a file path in game assets the requested data related to
  ## field - path to field of interest inside "original_file" json
  ## target_file - a framework file, containing the requested data
  data = ""
  try:
    with copen(target_file, "r", 'utf-8') as f:
      data = json.load(f)
  except:
    print("Warning: can not load file " + target_file)
    return None, -1
  index = -1
  for i, label in enumerate(data):
    if original_file in label["Files"] and (field in label["Files"][original_file]):
      index = i
      return data, i

  return None, -1



def replace(target_file, field, newdata, original):
  ## Tries to merge translation to framework
  ## if translation exists and conflicts with new one
  ## asks for user to manual merge
  ## target - file in framework related to file should be translated
  ## field - path of field in game assets json file which should be translated
  ## newdata - translated string
  ## original - path to file in game assets should be translated
  target = join(root_dir, target_file)
  data, index = get_data(field, target, original)
  if not (type(newdata) is str):
    return
  if data is None:
    print("Cannot get data: " + newdata)
    print("Target file: " + target)
    print("Assets file: " + original)
    return
  changed = False
  olddata = ""