#!/usr/bin/python
# -*- coding: utf-8 -*-

#Import the Natural Language Toolkit
import nltk
#Library to connect to MySQL from Python
import MySQLdb
#Library to run command line arguments from Python
import subprocess
#Library for sys.exit() and os version
import sys

#connect to the database
class DB:
  conn = None
  #self is the object of the class DB, used like "this" in Java
  def connect(self):
    #Connect to the local server and MySQL database
    self.conn = MySQLdb.connect('localhost', 'root', 'root', 'dict', charset="utf8")

  #Execute the "sql" query
  def query(self, sql):
    try:
      #The cursor is used to execute the query
      cursor = self.conn.cursor()
      cursor.execute(sql)

      #In case connection wasn't established, repeat the process
    except (AttributeError, MySQLdb.OperationalError):
      self.connect()
      cursor = self.conn.cursor()
      cursor.execute(sql)
    return cursor

def lookup(eng,count):
    print "Entered lookup for ",eng," Count: ",count
    db = DB()
    if count == 0:
      sql = "SELECT * FROM dictionary where English='"+eng+"'" #Error handling here!
    else:
      count = str(count)
      sql = "SELECT * FROM dictionary where English='"+eng+"' and Count='"+count+"'"
    cursor = db.query(sql)
    row = cursor.fetchone()
    if row == None:
      count = "0"
      sql = "SELECT * FROM dictionary where English='"+eng+"' and Count='"+count+"'"
      cursor = db.query(sql)
      row = cursor.fetchone()
    print "returned: ",row[1]," ",row[3]
    return row[1],row[3]

def translate(tagged):    

    flagQ = 0
    flagVerb = 0
    flagDont = 0
    flagCan = 0
    
    prevCount = 0
    
    subject = ""
    obj = ""
    verb = ""
    translatedSent = ""
    punctuation = ""
    count = 0
    index = 0
    indexStart = -1
    indexEnd = -1

    #Identify subject
    for word in tagged:
      if word[0] == "the":
        tagged.pop(index)
      if word[0] == "." or word[0] == "?":
        punctuation = word[0]
        tagged = tagged[:-1]
        break
      if "WP" in word or "WRB" in word:
        flagQ = 1
      if word[1][:2] == "VB":
        if indexStart == -1:
          indexStart = index
          print "Start: ",indexStart
      elif indexStart > -1 and flagVerb == 0:
        indexEnd = index
        flagVerb = 1
        print "End: ",indexEnd
      index = index + 1

    if flagQ == 1:
      o = tagged[:indexStart]
      v = tagged[indexStart:indexEnd]
      s = tagged[indexEnd:]
    else:
      s = tagged[:indexStart]
      v = tagged[indexStart:indexEnd]
      o = tagged[indexEnd:]

    temp = []
    if v == [] and len(tagged) > 2:
      for word in o:
        if word[0] == "dont":
          flagDont = 1
          v.insert(0,("do","VBP"))
          temp.insert(0,("not","RB"))
          continue
        temp.insert(word)
      o = temp

    index = 0
    for word in s:
      if word[0] == "can":
        s.pop(index)
        s.insert(index,("what","POS"))
        v.append(("can","POS"))
        break
      index = index + 1
        
    print "Subject: ",s
    print "Verb: ",v
    print "Object: ",o
    
    for word in s:
      trans,count = lookup(word[0], 0)
      if count < prevCount:
        count = prevCount
        prevCount = count
      else:
        subject = subject + trans + " "

    print "Translated Subject: ",subject
    temp = v
    for word in v:
      if "VBG" in word:
        index = v.index(word)
        temp[index], temp[index-1] = temp[index-1], temp[index]

    v = temp
    for word in v:
      print word[0]
      trans = lookup(word[0], count)[0]
      verb = verb + trans + " "

    print "Translated Verb: ",verb
    
    for word in o:
      trans = lookup(word[0], count)[0]
      obj = obj + trans + " "

    print "Translated Object: ",obj

    translated = subject + obj + verb + punctuation
    return translated

def checkContraction(sentence,word,num):
  flagContraction = sentence.find(word)
  if flagContraction >= 0:
    remove = word.find("'")
    word = word[:remove] + word[remove+1:]
    sentence = sentence[:flagContraction] + word + sentence[flagContraction+num:]
  return sentence

def findPunc(s,x):
  index = s.find(".",x)
  temp = index
  index = s.find("?",x)
  if index != -1 and temp != -1:
    if index > temp:
      index = temp
  elif index == -1:
    if temp != -1:
      index = temp
  return index

def preproc(sentence):
  #Bring the entire sentence into lowercase
  sentence = sentence.lower()
    
  #Look for contractions
  sentence = checkContraction(sentence,"don't",5)
  sentence = checkContraction(sentence,"isn't",5)
  flagIts = sentence.find("it's")
  #print "flagIts: ",flagIts
  if flagIts >= 0:
    sentence = sentence[:flagIts] + "it is" + sentence[flagIts+4:]
  print "\nSENTENCE: ",sentence.upper()

  #Tokenize the sentence to extract words and punctuation
  tokens = nltk.word_tokenize(sentence)

  #Tag the extracted tokens using a Part-of-Speech (POS) Tagger
  tagged = nltk.pos_tag(tokens)

  return tagged

def translatedSub():
    sentence = "What"
    tagged = preproc(sentence)
    #This is where the translator kicks in
    translated = translate(tagged)
    print "Translated: ",translated
    
translatedSub()
print ".srt successfully created!"
