# encoding: utf-8
# api: streamtuner2
# title: New favourite category
# description: Introduces new bookmarks categories
# version: 0.2
# type: feature
# category: ui
# config: -
# priority: optional
# 
# Adds a "New favourite category..." under Station > Extensions menu.
# New categories will show up in the bookmarks channel under favourite.
#

from uikit import *
from config import *

# 
class new_favourite_cat (object):
    plugin = "new_favourite_cat"
    meta = plugin_meta()
    parent = None
    w = None

    # hook up menu entry
    def __init__(self, parent):
        self.parent = parent
        uikit.add_menu([parent.extensions], "New favourite category…", self.win, insert=3)
        self.create_submenu(parent)
        self.update_submenu()
  
    # show input window
    def win(self, *w):
        w = self.w = gtk.Dialog(
            'New bookmark category',
            self.parent.win_streamtuner2, 
            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
            (gtk.STOCK_OK, gtk.RESPONSE_APPLY)
        )
        input = gtk.Entry(35)
        w.vbox.pack_start(input)
        log.UI(w.vbox.get_children())
        w.show_all()
        self.add(self.w, w.run(), input.get_text())

    # add category
    def add(self, w, r, title):
        bm = self.parent.bookmarks
        have = bm.streams.has_key(title)
        w.destroy()
        if r == gtk.RESPONSE_APPLY:
            log.NEW(title)
            if not have:
                bm.streams[title] = {}
        if r == gtk.RESPONSE_DELETE_EVENT:
            if have:
                bm.streams.remove(title)
        self.update_submenu()
        bm.update_categories()
        bm.display_categories()

    # introduce MenuItem+Menu
    def create_submenu(self, parent):
        self.submenu = gtk.Menu()
        for title, target, i in [("Bookmark to", parent.streammenu, 1), ("Add bookmark to", parent.streamactions, 3)]:
            mi = gtk.ImageMenuItem(gtk.STOCK_INDENT)
            mi.set_submenu(self.submenu)
            mi.set_label(title)
            mi.show_all()
            target.insert(mi, i)

    # bookmark to > … submenu w/ custom categories
    def update_submenu(self):
        bmc = self.parent.bookmarks.categories
        [self.submenu.remove(w) for w in self.submenu.get_children()]
        if len(bmc) >= 2 and type(bmc[1]) is list:
            for label in bmc[1]:
                uikit.add_menu([self.submenu], label, lambda w,target=label: self.parent.bookmark(w, target))
        self.submenu.show_all()
    
