#!/usr/bin/env python
# coding=UTF-8
"""
Xliff Time Zone Database's translation tool and files, automated by Google Translate API.
"""

__author__ = u"Matteo Bertamini, Luca D'Incà"
__copyright__ = u"Copyright 2017, Belka"
__license__ = u"MIT"
__maintainer__ = u"Matteo Bertamini"
__email__ = u"matteo@belka.us"

import sys, os.path, getopt
from language_tags import tags
from googleapiclient.discovery import build
import psycopg2
import urllib2
from xml.etree.ElementTree import Element, SubElement, Comment, ElementTree
from xml.etree import ElementTree as ET
import re, htmlentitydefs
# from ElementTree_pretty import prettify

def unescape(text):
    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    return unichr(int(text[3:-1], 16))
                else:
                    return unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass
        return text # leave as is
    return re.sub("&#?\w+;", fixup, text)


def main(argv):
    developerKey = os.environ.get('developerKey', '')
    helpOutput = 'xliffTimeZone.py [-o <outputfile>] [-k <developerkey>] <langtag>'
    outputfile = ''
    tag = ''

    #
    # 1 Params check and normalization
    #
    try:
        opts, args = getopt.getopt(argv, "ho:k:", ["ofile=", "developerKey="])
    except getopt.GetoptError:
        print helpOutput
        sys.exit(2)

    if (len(args) != 1):
        print helpOutput
        sys.exit(2)
    else:
        tag = tags.tag(args[0])

    for opt, arg in opts:
        if opt == '-h':
            print helpOutput
            sys.exit()
        elif opt in ("-o", "--ofile"):
            outputfile = os.path.split(arg)
        elif opt in ("-k", "--devkey"):
            developerKey = arg

    if not developerKey:
        print 'A developerKey shell variable or, a -k argument, must be defined'
        sys.exit(2)

    if outputfile == '':
        outputfile = (os.path.join(os.getcwd(), 'translations'), 'timezones.{}.xlf'.format(tag))
    else:
        if outputfile[0] == '':
            outputfile = (os.path.join(os.getcwd(), 'translations'), '{}.{}.xlf'.format(outputfile[1],tag))
        else:
            print 'only a filename without any path can be specified. The file will be written into the translations folder.'
            print helpOutput
            sys.exit(2)

    if not os.path.isdir(outputfile[0]):
        print 'Output path is incorrect: {} is not a dir'.format(outputfile[0])
        sys.exit(2)

    # building the final path
    outputfile = os.path.join(outputfile[0], outputfile[1])

    if not tag.valid:
        print 'Invalid lang tag: {}'.format(tag)
        print helpOutput
        sys.exit(2)


    #
    # 2 Preparing translation assets (DB + google + unicode)
    #
    cldrTz = False
    print u"Downloading latest unicode support for langtag {}...".format(tag)
    requestURL = u'http://www.unicode.org/repos/cldr/tags/latest/common/main/{}.xml'.format(tag.__str__().replace(U"-", "_"))
    try:
        cldrSource = urllib2.urlopen(requestURL)
    except urllib2.HTTPError as error:
        if error.code == 404:
            print u"The specified lang tag is not handled by the Unicode consortium: {}. Fallbacking to google translate".format(tag)
        else:
            print u"An unexpected error has occurred while downloading the unicode support data: {}. Fallbacking to google translate".format(error.reason)
    else:
        try:
            cldrRoot = ET.parse(cldrSource).getroot()
            cldrTz = cldrRoot.find('dates').find('timeZoneNames')
        except:
            print u"The unicode support for langtag {} seems not to be complete. Fallbaking on google translate".format(tag)


    service = build('translate', 'v2', developerKey=developerKey)
    translation = service.translations()


    conn_string = "host='pg' dbname='postgres' user='postgres' password='mysecretpassword'"
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()

    print("Database Connected, querying the timezones...")

    cursor.execute("SELECT tz.name AS measure FROM pg_timezone_names() tz;")
    timezones = cursor.fetchall()


    #
    # 3 Timezones translation
    #
    root = Element('xliff', {"version": "1.2", "xmlns": "urn:oasis:names:tc:xliff:document:1.2"})
    comment = Comment('Generated by Belka - www.belka.us')
    root.append(comment)

    file = SubElement(root, 'file',
                      {'source-language': '{}'.format('en'), 'datatype': 'plaintext', 'original': 'postgresql'})

    body = SubElement(file, 'body')

    for timezone in timezones:
        exemplarCity = None
        print u"Translating: {}".format(timezone[0])

        if type(cldrTz) is Element:
            exemplarCity = cldrTz.find(u"zone[@type='{}']/exemplarCity".format(timezone[0]))

        # google translate fallback
        if exemplarCity is None:
            print "Fallbacking to google translate"
            # parse string
            normalizedLine = u'"' + unicode(timezone[0].replace(u'_', u' ').replace(u'"', u'')) + u'"'
            lineTranslated = u''

            sublines = normalizedLine.split(u'/')

            try:
                for word in sublines:
                    wordTranslated = translation.list(
                        source='en',
                        target=tag,
                        q=[word]
                    ).execute()

                    lineToken = unescape(wordTranslated['translations'][0]['translatedText']).strip('"').strip(' ').strip('/')
                    lineTranslated += unicode(u'/{}'.format(lineToken))
            except:
                lineTranslated = normalizedLine.strip('"')
                print "Google translate can't translate it. Writing as-is: {}".format(lineTranslated)

            lineTranslated = lineTranslated.strip('/')
        else:
            lineTranslated = exemplarCity.text

        transUnit = SubElement(body, u'trans-unit', {'id': u'timezone_{}'.format(timezone[0])})
        source = SubElement(transUnit, 'source')
        source.text = u'{}'.format(timezone[0])
        target = SubElement(transUnit, 'target')
        target.text = u'{}'.format(lineTranslated)
        print ""

    print "Translated. Writing xliff..."

    ElementTree(root).write(outputfile)

    print ""
    print "Done."


if __name__ == "__main__":
   main(sys.argv[1:])
