# -*- coding: utf-8 -*-
import pluginsystem, configsystem, hmsystem
from threading import Thread
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from QGlobalFilter import QGlobalFilter
from QCustomTabWidget import QCustomTabWidget
import globalvars as g

class QConsole(QWidget):
  def __init__(self):
    QWidget.__init__(self)
    self.hms = hmsystem.HMSystem(self)
    self.hms.initHM()
    self.watcher = QFileSystemWatcher(self)
    self.loadGconfig(self)
    self.setAttribute(Qt.WA_TranslucentBackground)
    self.setObjectName("mainWidget")
    self.tabwidget = QCustomTabWidget(self)
    self.tabwidget.tabAddRequested()
    self.giveFocus()
    self.mainLayout = QVBoxLayout(self)
    self.mainLayout.setObjectName("mainLayout")
    self.mainLayout.setContentsMargins(0, 0, 0, 0)
    self.mainLayout.addWidget(self.tabwidget)
    self.globalFilter = QGlobalFilter(self)
    self.connect(self, QtCore.SIGNAL("toggle_visibility(PyQt_PyObject)"), self.toggleVisibility)
    self.connect(self.watcher, QtCore.SIGNAL("fileChanged(QString)"), self.loadGconfig)
    self.connect(self, QtCore.SIGNAL("giveFocus()"), self.giveFocus)
    QCoreApplication.instance().installEventFilter(self.globalFilter)
    self.show()

  def loadGconfig(self, config):
    tmpconfig = []
    pluginsystem.trigger_event("get_config",  config=tmpconfig, plugin="jake")
    self.gconfig = tmpconfig[0]
    if self.gconfig['alwaysontop']:
      self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
    else:
      self.setWindowFlags(Qt.FramelessWindowHint)
    qscreen = QDesktopWidget()
    screen = qscreen.screenGeometry()
    self.gsizew = screen.width() * (self.gconfig['appwidth'] / 100.0)
    self.gsizeh = screen.height() * (self.gconfig['appheight'] / 100.0)
    self.resize(self.gsizew, self.gsizeh)
    self.move(((screen.width() - self.geometry().width()) / 2) + (self.gconfig['screen'] * screen.width()) , 0)
    self.setWindowTitle(g.wname + " " + g.version)
    g.set_prompt(self.gconfig['prompt'])
    styleData = QFile(self.gconfig['skin'])
    styleReader = QTextStream(styleData)
    if styleData.open(QIODevice.ReadOnly | QIODevice.Text):
      self.setStyleSheet(styleReader.readAll())
    styleData.close()
    self.toggleVisibility(g.fakeSHEvent())
    if not self.watcher.files().contains(g.jake_config_path + "config"):
      self.watcher.addPath(g.jake_config_path + "config")

  def toggleVisibility(self, e):
    if e.Key == g.shkey:
      self.setVisible(self.isHidden())
      if self.hms.mustFocus() and self.isVisible():
        thread = Thread(target=self.hms.focus)
        thread.start()

  def giveFocus(self):
    self.tabwidget.currentWidget().child().setFocus(Qt.OtherFocusReason)