from . import widget
from browser import html, document

class Menu(html.UL, widget.Widget):
    def __init__(self, id=None, style={}):
        default_style = dict(position= 'relative', height='auto',
            width='auto')
        default_style.update(style)
        html.UL.__init__(self, Class="ui-widget ui-menu", style=default_style)
    
        widget.Widget.__init__(self, self, 'menu', id)
        document.bind('click', self.leave)
        self.active = False

    def add(self, title):
        item = MenuItem(title, Class="ui-widget ui-menu-item")
        item.bind('click', item.activate)
        item.bind('mouseenter', item.enter)
        self <= item
        return item

    def leave(self, ev):
        for child in self.children:
            if child.state == 'show':
                document.remove(child.div)
                child.state = 'hide'
        self.active = False

class MenuItem(html.LI):

    def __init__(self, *args, **kw):
        html.LI.__init__(self, *args, **kw)
        self.items = []
        self.state = "hide"

    def activate(self, ev):
        self.parent.active = True
        self.show(ev)
        ev.stopPropagation()

    def enter(self, ev):
        if self.parent.active:
            self.show(ev)

    def show(self, ev):
        for item in self.parent.children:
            if item.state == "show":
                if item == self:
                    return
                document.remove(item.div)
                item.state = "hide"
        if self.state == "hide":
            left = ev.target.left
            top = ev.target.top+ev.target.height

            self.div = html.DIV(Class="ui-widget ui-menu-sublist",
                style=dict(position='absolute', left=left, top=top, zIndex=99))
            for item in self.items:
                line = html.DIV(item[0], Class="ui-menu-subitem")
                if item[1] is not None:
                    line.bind('click', item[1])
                self.div <= line
            self.state = "show"
            self.div.style.borderWidth = "1px"
            document <= self.div
        else:
            document.remove(self.div)
            self.state = "hide"

    def add(self, label, callback = None):
        self.items.append((label, callback))
