import pygtk
pygtk.require("2.0")

import gtk
import templateview
import random

class TemplateControl(gtk.VBox):

    def __init__(self, markov, base_template):
        gtk.VBox.__init__(self)
        self.__markov = markov
        self.__base = base_template
        self.__history = [base_template.clone()]
        self.__blocked = 0

        frame = gtk.Frame()
        self.__view = templateview.TemplateView()
        frame.add(self.__view)

        self.pack_start(frame, expand=1, fill=1)
        frame.show_all()

        self.__status_label = gtk.Label("")
        self.pack_start(self.__status_label, expand=0, fill=1, padding=4)

        sep = gtk.HSeparator()
        self.pack_start(sep, expand=0, fill=1, padding=2)
        sep.show()

        bbox = gtk.HButtonBox()
        self.pack_start(bbox, expand=0, fill=1)

        b_back = gtk.Button("Back")
        bbox.pack_start(b_back, expand=0, fill=0)
        b_back.connect("clicked", lambda b, tc: tc.back(), self)

        b_step = gtk.Button("Step")
        bbox.pack_start(b_step, expand=0, fill=0)
        b_step.connect("clicked", lambda b, tc: tc.step(), self)

        b_fill = gtk.Button("Fill")
        bbox.pack_start(b_fill, expand=0, fill=0)
        b_fill.connect("clicked", lambda b, tc: tc.fill(), self)

        bbox.show_all()

        self.refresh()


    def refresh(self):
        if self.__history:
            template = self.__history[-1]
            self.__view.set_template(template)

            msg = "completed syllables = %d, metric error = %.1f" % \
                  (template.completed_syllables(), template.get_metric_error())
        else:
            self.__view.set_template(None)
            msg = ""

        if self.__blocked:
            msg += ' <b><span color="red">BLOCKED</span></b>'
        elif self.__history and self.__history[-1].is_finished():
            msg += ' <b><span color="blue">Complete</span></b>'

        self.__status_label.set_markup(msg)


    def step(self):
        if not self.__history:
            self.__history.append(self.__base.clone())

        if self.__history[-1].is_finished():
            return

        step = self.__history[-1].clone()
        success = step.step(self.__markov)

        if success:
            self.__history.append(step)
        else:
            self.__blocked = 1

        self.refresh()


    def back(self):
        self.__blocked = 0
        if self.__history:
            self.__history.pop()
        if not self.__history:
            self.__history.append(self.__base.clone())
        self.refresh()


    def fill(self):
        def fill_cb(tc):
            tc.step()
            if self.__blocked:
                i = random.randint(1, len(self.__history)-1)
                self.__history = self.__history[:i]
                self.__blocked = 0
                self.refresh()
            return not tc.__history[-1].is_finished()
        gtk.timeout_add(50, fill_cb, self)
        

            

    
