#!/usr/bin/env python3

# http://inamidst.com/saxo/
# Created by Sean B. Palmer

import json
import saxo

def optflag(arg):
    flag = None
    if arg.startswith(":"):
        if " " in arg:
            flag, arg = arg.split(" ", 1)
        else:
            flag, arg = arg, ""
        flag = flag[1:]
    return flag, arg

def translate(text, source="auto", target=None):
    phonetic = False

    if target == "p":
        target = "en"
        phonetic = True
    elif target is None:
        target = "en"

    text = text.strip('" ')
    page = saxo.request(
        "http://translate.google.com/translate_a/t",
        modern=True,
        query = {
            "client": "t",
            "hl": "en",
            "sl": source,
            "tl": target,
            "multires": "1",
            "otf": "1",
            "ssel": "0",
            "tsel": "0",
            "sc": "1",
            "text": text
        })

    text = page["text"]
    while ",," in text:
        text = text.replace(",,", ",null,")
    text = text.replace("[,", "[null,")
    text = text.replace(",]", ",null]")

    try: js = json.loads(text)
    except ValueError:
        return "Problem loading the JSON"

    if not phonetic:
        translation = "".join(t[0] for t in js[0])
    else:
        translation = js[0][0][3] or js[0][0][0]
    source = js[2]
    return translation.replace(" ,", ","), source, target

@saxo.pipe
def tr(arg):
    if not arg:
        return "Translate text from one language to another"

    source, arg = optflag(arg)
    target, text = optflag(arg)

    translation, source, target = translate(text, source, target)

    t = translation[:-1] if translation.endswith(".") else translation
    msg = "%s (%s » %s). translate.google.com"
    return msg % (translation, source, target)
