import os, gtk, gtksourceview2
import glitch
from glitch import *

_default="""import glitch, glitch.gtk
from glitch.limbo.objects import Square
cam=glitch.gtk.GtkCamera(children=[
        Square()])

cam.run()
"""

class Start(gtk.Window):
    def __init__(self, *args, **kwargs):
        gtk.Window.__init__(self)
        self.set_title("The Dagger")

        self.glue = gtk.VBox()
        self.add(self.glue)

        self.srcview = self._srcview()
        sw = gtk.ScrolledWindow()
        sw.add(self.srcview)

        toolbar=self._toolbar()

        self.nodes=self._nodes()

        hp= gtk.HPaned()
        hp.add1(self.nodes)
        hp.add2(sw)

        self.glue.pack_start(toolbar, False)
        self.glue.pack_start(hp)

    def do_run(self, *args):
        src= self.srcview.get_buffer().get_text(*self.srcview.get_buffer().get_bounds())
        exec(src, {})

    def do_open(self, *args):
        f=gtk.FileChooserDialog(action=gtk.FILE_CHOOSER_ACTION_OPEN,buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        response = f.run()
        if response == gtk.RESPONSE_OK:
            self.outfile=f.get_filename()
            self.srcview.get_buffer().set_text(open(self.outfile).read())
        f.destroy()

    def do_save(self, *args):
        if not hasattr(self, "outfile"):
            f=gtk.FileChooserDialog(action=gtk.FILE_CHOOSER_ACTION_SAVE,buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
            response = f.run()
            if response == gtk.RESPONSE_OK:
                self.outfile=f.get_filename()
                self.do_save()
            f.destroy()
        else:
            src= self.srcview.get_buffer().get_text(*self.srcview.get_buffer().get_bounds())
            open(self.outfile, 'w').write(src)

    def _srcview(self):
        mgr = gtksourceview2.LanguageManager()
        python = mgr.get_language('python')
        buffer = gtksourceview2.Buffer()
        buffer.set_language(python)
        buffer.set_text(_default)
        return gtksourceview2.View(buffer)

    def _nodes(self):
        vp = gtk.VPaned()

        ls = gtk.ListStore(str)
        for node in dir(glitch):
            if isinstance(getattr(glitch, node), type):
                ls.append([node])

        tv = gtk.TreeView(ls)
        renderer = gtk.CellRendererText()
        col= gtk.TreeViewColumn("Nodes", renderer)
        col.add_attribute(renderer, "text", 0)

        mgr = gtksourceview2.LanguageManager()
        python = mgr.get_language('python')
        docbuffer=gtksourceview2.Buffer()
        docbuffer.set_language(python)
        docs=gtksourceview2.View(docbuffer)

        def on_change(tv):
            (model, iter)=tv.get_selection().get_selected()
            sel= model.get_value(iter, 0)
            cls=eval(sel, globals())
            mod=eval(cls.__module__, globals())
            f=mod.__file__.replace('pyc', 'py')
            docbuffer.set_text(open(f).read())

        tv.connect('cursor-changed', on_change)

        tv.append_column(col)

        sc_tv=gtk.ScrolledWindow()
        sc_tv.set_size_request(200,400)
        sc_tv.add(tv)

        sc_docs=gtk.ScrolledWindow()
        sc_docs.add(docs)

        vp.add1(sc_tv)
        vp.add2(sc_docs)
        return vp

    def _toolbar(self):
        toolbar = gtk.Toolbar()
        items = [("execute", gtk.STOCK_EXECUTE, self.do_run),
                 ("save", gtk.STOCK_SAVE, self.do_save),
                 ("open", gtk.STOCK_OPEN, self.do_open),
                 ("close", gtk.STOCK_CLOSE, lambda w: gtk.main_quit())]
        for (label, icon, fn) in items:
            b = gtk.ToolButton(icon)
            b.set_label(label)
            toolbar.insert(b, 0)
            b.connect("clicked", fn)
        return toolbar

if __name__=='__main__':
    s = Start()
    s.show_all()
    s.connect('destroy', lambda w: gtk.main_quit()) # todo: save?
    gtk.main()
