import json
from subprocess import call

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)
			#print lineSplitArray
			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

	#print len(enDict)
	#print len(desciptionDict)

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

def json_to_strings(dict):
	stringsFile = open('Strings.h','w')
	tempStrings = open('tempStrings.h','w')
	stringsFile.write('#import \"OTRLanguageManager.h\"\n\n')

	stringsFile.write('// DO NOT EDIT THIS FILE. EDIT strings.json then run python StringsConverter.py\n\n')

	for key in dict:
		line = '#define '+key+' [OTRLanguageManager translatedString: '+add_obj_c(dict[key]['string'])+']'
		stringsFile.write(line+'\n')
		line = 'NSLocalizedString('+add_obj_c(dict[key]['string'])+','+add_obj_c(dict[key]['comment'])+')'
		tempStrings.write(line+'\n')

	#Special case for .h file where always display the 'Default' in iOS system language
	default = 'NSLocalizedString(@\"Default\", @\"default string to revert to normal language behaviour\")'
	stringsFile.write('#define DEFAULT_LANGUAGE_STRING '+default)
	tempStrings.write(default)

	stringsFile.close()
	tempStrings.close()

def genStrings(fileName):
	call(['genstrings',fileName])
	call(['mv','./Localizable.strings','en.lproj/Localizable.strings'])
	



if __name__ == "__main__":
	#fileString = "Strings.h"
	jsonFileString = 'strings.json'
	#file = open(fileString,'r')
	
	#convert_to_json(file)

	#file.close()
	file = open(jsonFileString,'r')
	json_to_strings(json.load(file))
	file.close()

	fileName = 'tempStrings.h'
	genStrings(fileName)
	call(['rm','-rf',fileName])
