#!/usr/bin/python
# -*- coding: utf-8 -*-
from googletranslate.PyGoogleTranslate import GoogleTranslate
import sys
import os
from optparse import OptionParser
SRC_LANG = ''
DEST_LANG = 'en'
RAW = False
OUTPUT_FILE = None

parser = OptionParser()
parser.description ="Translate text using Google Ajax API"
parser.add_option("-o","--output-file",
       action="store", dest="output_file", default=None,
       help="An output file into which the entire translated output is written")
parser.add_option("-i","--input",
       action="store",dest="input",default="stdin",
       help="How input is provided to this script. Default is stdin but you can specify a file")
parser.add_option("-s","--src-lang",
       action="store", dest="src_lang", default=SRC_LANG,
       help="Define the source language (i.e. what you want to translate). Auto-detected if not specified")
parser.add_option("-d","--dest-lang",
       action="store", dest="dest_lang", default='en',
       help="Define the destination language. Default is %s"%DEST_LANG)
parser.add_option("-r","--raw",
       action="store_true", dest="raw", default=RAW,
       help="If specified the script will return raw urlencoded data from Google. Otherwise it will attempt to convert to utf8")
(options,args) = parser.parse_args()

container = []
gt = GoogleTranslate()

if options.output_file:
  f = os.path.abspath(options.output_file)
  try:
    fd = open(f,'w')
  except IOError:
    fd.close()
    sys.stderr.write("You don't have permission to write to %s\n"%f)
    sys.exit(1)
  else:
    OUTPUT_FILE = f
    fd.close()

def write_output(f,t):
  """This function is to avoid needing to duplicate the code for writing to the output file """
  fd = open(f,'w')
  fd.write(t)
  fd.close()

if options.input.lower() == 'stdin':
  for x in sys.stdin.readlines():
    container.append(x)
  fullString = "".join(container)
  returned = gt.translate(fullString,srcLang=options.src_lang,destLang=options.dest_lang,raw=options.raw)
  if not OUTPUT_FILE:
    print returned
  else:
    write_output(OUTPUT_FILE,returned)
else:
  if os.path.isfile(os.path.abspath(options.input)) and os.access(os.path.abspath(options.input),os.R_OK):
    try:
      fd = open(os.path.abspath(options.input))
    except IOError:
      raise
    else:
      for x in fd.readlines():
        container.append(x)
      fullString = "".join(container)
      returned = gt.translate(fullString,srcLang=options.src_lang,destLang=options.dest_lang,raw=options.raw)
      if not OUTPUT_FILE:
        print returned
      else:
        write_output(OUTPUT_FILE,returned)
    finally:
      fd.close()
  else:
    sys.stderr.write("Could not open file %s for reading or that file does not exist\n"%os.path.abspath(options.input))
    sys.exit(1)

