# -*- coding: utf-8 -*-
# adesk "Bookmarks" plugin

name = "Bookmarks"
desc = "Bookmarks ( .gtk-bookmarks )"
icon = 'images/bookmarks.png'

import gtk
import os

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

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

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

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

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

        box = gtk.VBox(False, 0)
        box.set_border_width(0)

        scrolled = gtk.ScrolledWindow()
        scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        scrolled.add_with_viewport(box)
        self.add(scrolled)
        scrolled.show()

        home = os.environ['HOME']

        box.pack_start(self.add_bookmark('Home', home), False, False)
        box.pack_start(self.add_bookmark('File System', '/'), False, False)
        box.pack_start(gtk.HSeparator(), False, False)

        if os.access("%s/.gtk-bookmarks" % home, os.F_OK|os.R_OK):
            f = open("%s/.gtk-bookmarks" % home,'r')
            for line in f:
                if line == '\n' or line[0]=='#':
                    continue
                else:
                    line = line.strip('\n')
                    tmp = line.split(' ',1)

                    if len(tmp) >= 2:
                        bm_path = tmp[0].strip(' ')
                        lbl = tmp[1].strip(' ')
                    else:
                        bm_path = tmp[0].strip(' ')
                        lbl = tmp[0].split('/')[-1]

                    box.pack_start(self.add_bookmark(lbl, bm_path),False,False)
            f.close()

        self.set_size_request(300,300)
        box.show_all()

    def add_bookmark(self, label, path):
        if label == 'Home':
            image = 'images/plugins/bookmarks/home.png'
        elif path == '/':
            image = 'images/plugins/bookmarks/computer.png'
        else:
            image = 'images/plugins/bookmarks/folder.png'
        button = Core.image_button(label, image, 24)
        button.connect("button-release-event", self.onClicked, path)
        return button

    def onClicked(self, widget, event, path):
        Core.launch_command('%s %s' % (self.plugin.settings['filemanager'], path))
        self.toggle()
