#!/usr/bin/python
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import sys, os
import threading, Queue
from time import time
from time import sleep
import traceback
import re
import shutil
import codecs
import zlib
import zipfile
import StringIO
import subprocess as sub

from p4util import P4File

# BEGIN: Import LocaleInfo
strBase = os.getcwd()
strServerDir = os.path.join(strBase, 'server')
sys.path.insert(0, strServerDir)
from LocaleInfo import LocaleInfo
# END: Import LocaleInfo

def FindLine(astrLines, strLine):
	i = 0
	while i < len(astrLines):
		if astrLines[i].strip() == strLine:
			return i
		i += 1

	print "couldn't find line: " + strLine
	raise 1

def ReplaceGeneratedCode(strContents, strKey, strInsert):
	astrContents = strContents.split('\n')
	astrComments = [
		'		// This is generated by bin/loc/updateLocales.py using server/LocaleInfo.py as the source',
		'		// To modify locale information, edit server/LocaleInfo.py',
		'		// To modify the code produced, edit bin/loc/updateLocales.py']

	astrInsert = strInsert.split('\n')
	
	iBeginComment = FindLine(astrContents, "// BEGIN:AUTO_GENERATED:" + strKey)
	iEndComment = FindLine(astrContents, "// END:AUTO_GENERATED:" + strKey)
	
	return '\n'.join(astrContents[0:iBeginComment+1] + astrComments + astrInsert + astrContents[iEndComment:])

def ReplaceGeneratedCode2(strContents, strKey, strInsert):
	astrContents = strContents.split('\n')
	astrInsert = strInsert.split('\n')
	
	iBeginComment = FindLine(astrContents, "<!--BEGIN:AUTO_GENERATED:" + strKey + "-->")
	iEndComment = FindLine(astrContents, "<!--END:AUTO_GENERATED:" + strKey + "-->")
	
	return '\n'.join(astrContents[0:iBeginComment+1] + astrInsert + astrContents[iEndComment:])

def UpdateHtml():
	strBaseDir = os.path.join(os.getcwd(), 'website','app')

	for strFile in ['noaccess.html', 'noaccess_guest.html', 'noaccess_registered.html']:
		for dLocaleInfo in LocaleInfo.LocaleListSortedByName():
			astrLocaleLinks = []
			for dLocaleInfo2 in LocaleInfo.LocaleListSortedByName():
				strClass = ''
				if dLocaleInfo2['locale'] == dLocaleInfo['locale']:
					strClass = 'selected'
				astrLocaleLinks.append('\t<a href="/?locale=' + dLocaleInfo2['locale'] + '" class="' + strClass + '">' + dLocaleInfo2['name'] + '</a>')
			strFooterLocaleLinks = "\n\t\t|\n".join(astrLocaleLinks)

			strPath = os.path.join(strBaseDir, dLocaleInfo['locale'], strFile)
			try:
				fin = open(strPath, 'rb')
				strContents = fin.read()
				fin.close()
			except:
				strPath = strPath.replace(dLocaleInfo['locale'], 'en_US')
				print "Reading contents from en_US location: ", strPath
				fin = open(strPath, 'rb')
				strContents = fin.read()
				fin.close()
			
			try:
				strOut = ReplaceGeneratedCode2(strContents, "FooterLocaleList", strFooterLocaleLinks)
			except:
				print "Error writing", strPath
				print "strContents"
				print strContents
				raise

			P4File.p4write(strPath, strOut, "updateLocales")
	
def UpdateLocaleInfoAs():
	print "Updating LocaleInfo.as"

	strPath = os.path.join(os.getcwd(), 'as','util','picnik','util','LocaleInfo.as')

	fin = open(strPath, 'rb')
	strContents = fin.read()
	fin.close()
	strInsert =  "\t\tstatic private var _aobAllLocales:Array = [\n\t\t\t"
	fFirst = True

	for dLocaleInfo in LocaleInfo.LocaleListSortedByName():
		if not fFirst:
			strInsert += ",\n\t\t\t"
		strLine = "{"
		fFirstKey = True
		
		# these are the keys we are interested in
		
		dKeys = {
						'label':{'fnGet':lambda x : x['name']},
						'locale':{'sortPriority':0},
						'flag':{'fnGet':lambda x : x['locale'][3:].lower()},
						'useSystemFont':{},
						'nonBold':{},
						'countries':{},
						'googleCode':{},
						'googlePlus':{'fOptional':True}
						}
		
		atKeys = sorted(dKeys.items(), key=lambda t: (t[1].get('sortPriority', 100), t[0]))
		
		for atKeys in atKeys:
			strKey, dKeyInfo = atKeys
			
			if 'fnGet' in dKeyInfo:
				obVal = dKeyInfo['fnGet'](dLocaleInfo)
			else:
				if not (strKey in dLocaleInfo):
					if dKeyInfo.get('fOptional', False):
						continue
					else:
						print "ERROR: Locale missing field: " + strKey
						print dLocaleInfo
						sys.exit(1)
				obVal = dLocaleInfo[strKey]

			if not fFirstKey:
				strLine += ", "
			fFirstKey = False

			strLine += strKey + ": "
			if type(obVal) == type(True):
				strLine += str(obVal).lower()
			elif type(obVal) == type([]):
				strLine += str(obVal)
			else: # everything else is a string
				strLine += "'" + str(obVal) + "'"
				
		strLine += "}"
		strInsert += strLine
		fFirst = False
	strInsert += "\n\t\t];\n"

	strOut = ReplaceGeneratedCode(strContents, "LocaleInfo", strInsert)

	P4File.p4write(strPath, strOut, "updateLocales")

def PrintLocaleInfo():
	print "---- Nicely formatted version of dLocales in LocaleInfo ----"
	dLocales = LocaleInfo.dLocales
		
	print """	dLocales = {"""
	
	astrLocalesOut = []
	
	astrKeys = dLocales.keys()
	astrKeys.sort()
	for strLocaleCode in astrKeys:
		strLocaleOut = "		'" + strLocaleCode + "' : {\n"
		dLocaleInfo = dLocales[strLocaleCode]
		dLocaleInfo['countries'].sort()
		if not 'googleCode' in dLocaleInfo:
			dLocaleInfo['googleCode'] = '#### INSERT CODE HERE ####'
		astrPropLines = []
		astrProps = dLocaleInfo.keys()
		astrProps.sort()
		for strProp in astrProps:
			astrPropLines.append("				 " + str({strProp:dLocaleInfo[strProp]})[1:-1])
		strLocaleOut += ",\n".join(astrPropLines)
		strLocaleOut += "}"
		astrLocalesOut.append(strLocaleOut)
	print ",\n".join(astrLocalesOut)
	print "		}"

# PrintLocaleInfo()
UpdateLocaleInfoAs()
# UpdateHtml()
