# -*- coding: utf-8 -*-

import gtk
import vte
import os

import adesk.plugin as Plg
import adesk.core as Core
import adesk.ui as UI

try:
    import vte
except:
    Core.logINFO('Plugin "terminal" need python-vte')
    Core.logINFO(' -- debian/ubuntu : "sudo apt-get install python-vte"')

class Plugin(Plg.Plugin):
    def __init__(self, bar, settings):
        Plg.Plugin.__init__(self, bar, settings)
        self.can_zoom = True
        self.settings = settings
        self.terminal = Terminal(self, bar)

    def onClick(self, widget, event):
        self.terminal.toggle()

    def resize(self):
        self.set_size_request(self.cfg['icon_size'], self.cfg['icon_size'])

class Terminal(UI.PopupWindow):
    def __init__(self, plugin, bar):
        UI.PopupWindow.__init__(self, bar, plugin)

        self._vte = vte.Terminal()
        #~ self.connect("focus-in-event", self.fixFocus)
        self._vte.set_emulation("xterm")
        self._vte.set_font_from_string(plugin.settings['font'])
        self._vte.set_allow_bold(True)
        self._vte.set_scrollback_lines(1024)
        self._vte.set_size_request(int(plugin.settings['width']), int(plugin.settings['height']))

        if self.is_composited():
            self._vte.set_opacity(int(65535 * int(plugin.settings['opacity']) / 100))
        else:
            self._vte.set_background_transparent(True)

        self._vte.show()
        box = gtk.HBox(False, 4)
        self.add(box)
        box.add(self._vte)
        box.show()
        scrollbar = gtk.VScrollbar()
        scrollbar.show()
        scrollbar.set_adjustment(self._vte.get_adjustment())
        box.add(scrollbar)

        self.init_term()
        self._vte.connect("child-exited", self.__cb_exited)

        ## exec cmd
        if not plugin.settings['exec_cmd'] == '':
            self._vte.feed_child('%s\n' % plugin.settings['exec_cmd'])

    def init_term(self):
        os.chdir(os.getenv('HOME'))
        self._vte.fork_command()
        realpath = os.path.dirname(os.path.realpath( __file__ ))
        os.chdir(realpath + '/..')

    def __cb_exited(self, terminal):
        self.init_term()
        self.toggle()

