# -*- coding: utf-8 -*-
import sys, urllib, tempfile, pluginsystem
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from QCustomTextCursor import QCustomTextCursor
import globalvars as g
import utils as u

#Locale support
try:
  LOCALE_DIR = "locale"
  t = gettext.translation("main", LOCALE_DIR)
  _ = t.ugettext
except:
  _ = u.fake_locale

class QCustomTextBrowser(QTextBrowser):
  def __init__(self, parent=None):
    QTextBrowser.__init__(self, parent)
    self.parent = parent
    self.setObjectName("textBrowser")
    self.setAttribute(Qt.WA_DeleteOnClose)
    self.commandHistory = []
    self.commandHistory.append("")
    self.commandHistoryIndex = 0
    self.setAcceptRichText(True)
    self.setReadOnly(True)
    self.setOpenExternalLinks(True)
    self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
    self.cursor = QCustomTextCursor(self)
    self.scrollBar = self.verticalScrollBar()
    self.installEventFilter(self)
    if len(g.welcomemsg) > 0:
      self.printString(g.welcomemsg, False, False)
    self.printString("", True, len(g.welcomemsg) > 0)
    self.cursor.updateLastEnterPos()

  def getCursor(self):
    return self.cursor

  def keyPressEvent(self, e):
    if (e.key() == Qt.Key_Return or e.key() == Qt.Key_Enter) and (e.modifiers() & Qt.ControlModifier):
      self.printString("", False, True)
    elif e.key() == Qt.Key_Return or e.key() == Qt.Key_Enter:
      self.cursor.moveToEnd()
      self.cursor.setPosition(self.cursor.lastEnterPos)
      self.cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
      cmd = unicode(self.cursor.selection().toPlainText()[:-len(g.cursorChar)])
      self.cursor.clearSelection()
      self.printString("", False, True)
      pluginsystem.trigger_event("analyze_command",  data=cmd,  obj=self)
      self.printString("", True, True)
      self.cursor.deleteUpperEmptyLine()
      self.cursor.updateLastEnterPos()
      self.commandHistory.append(cmd)
      self.commandHistoryIndex = len(self.commandHistory)
      self.scrollBar.setValue(self.scrollBar.maximum())
    elif e.key() == Qt.Key_Backspace:
      self.cursor.keyBackspacePreviousCharacter()
    elif e.key() == Qt.Key_Delete:
      self.cursor.keyDeletePreviousCharacter()
    elif e.key() == Qt.Key_Space:
      self.cursor.keySpace()
    elif e.key() == Qt.Key_Up:
      self.cursor.selectAll()
      self.cursor.removeSelectedText()
      if self.commandHistoryIndex == 0:
        self.commandHistoryIndex = len(self.commandHistory)-1
      else:
        self.commandHistoryIndex -= 1
      self.printString(self.commandHistory[self.commandHistoryIndex], True, False)
    elif e.key() == Qt.Key_Down:
      self.cursor.selectAll()
      self.cursor.removeSelectedText()
      if self.commandHistoryIndex == len(self.commandHistory):
        self.commandHistoryIndex = 1
      else:
        if self.commandHistoryIndex == len(self.commandHistory)-1:
          self.commandHistoryIndex = 0
        else:
          self.commandHistoryIndex += 1
      self.printString(self.commandHistory[self.commandHistoryIndex], True, False)
    elif e.key() == Qt.Key_Left:
      self.cursor.moveLeft()
    elif e.key() == Qt.Key_Right:
      self.cursor.moveRight()
    elif e.key() == Qt.Key_Tab:
      text = self.cursor.findAllMinusLastWord()
      cmd = self.cursor.findLastWord()
      if not len(cmd) == 0:
        capabilities = []
        for capability in pluginsystem.capabilities:
          if capability.startswith(cmd):
            capabilities.append(capability)
        capabilities.sort(key=unicode.lower)
        if len(capabilities) == 1:
          self.printString(text + capabilities[0], True, False)
        elif len(capabilities) > 1:
          autocompletecmd = u.findAutocompleteCommand(capabilities)
          if autocompletecmd == cmd:
            output = u.commands2table(self, capabilities)
            self.printString(output, False, False)
            self.cursor.updateLastEnterPosWithLen(len(g.prompt))
            self.printString(cmd, True, True)
          else:
            self.printString(text + autocompletecmd, True, False)
      else:
        output = u.commands2table(self, pluginsystem.capabilities)
        self.printString(output, False, False)
        self.cursor.updateLastEnterPosWithLen(len(g.prompt))
        self.printString(cmd, True, True)
    else:
      self.cursor.insertCharacter(e.text())

  def printString(self, s, withPrompt=False, newLine=False):
    self.cursor.printString(s, withPrompt, newLine)

  def loadResource(self, type, name):
    url = str(name.toString())
    ret = QVariant()
    if url.startswith('http://'):
      tmpFile = tempfile.mkstemp()
      tmpFile = str(tmpFile[1])
      urllib.urlretrieve(url, tmpFile)
      ret = QTextBrowser.loadResource(self, type, QUrl(tmpFile))
    else:
      ret = QTextBrowser.loadResource(self, type, name)
    return ret