from gi.repository import GObject, Gtk, Gdk
import os, sys, glob
import config

class ModelSelector(Gtk.Dialog):
    def __init__(self, xml_filename = '', asr_model = ''):
        super(ModelSelector, self).__init__()
        self.add_button("Cancel", Gtk.ResponseType.CANCEL)
        self.add_button("OK", Gtk.ResponseType.OK)
        box = self.get_content_area()

        xml_box = Gtk.HBox()
        xml_box.pack_start(Gtk.Label('XML file:'), False, False, 10)
        xml_entry = Gtk.Entry()
        xml_entry.set_text(xml_filename)
        xml_entry.set_width_chars(len(xml_filename))
        self.xml_entry = xml_entry
        xml_box.pack_start(xml_entry, True, True, 10)
        xml_button = Gtk.Button("Choose...")
        xml_button.connect('clicked', self.show_filechooser)
        xml_box.pack_start(xml_button, False, False, 10)

        box.pack_start(xml_box, False, False, 5)

        model_box = Gtk.HBox()
        model_box.pack_start(Gtk.Label('ASR model:'), False, False, 10)
        model_chooser = Gtk.ComboBoxText()
        model_chooser.set_entry_text_column(0)
        for i, model in enumerate(self.list_models()):
            model_chooser.append_text(model)
        model_chooser.set_active(0)
        self.model_chooser = model_chooser
        model_box.pack_start(model_chooser, True, True, 10)

        box.pack_start(model_box, False, False, 5)
        self.show_all()

    def show_filechooser(self, button):
        dialog = Gtk.FileChooserDialog("Please choose a file", self, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
        filter_text = Gtk.FileFilter()
        filter_text.set_name("XML files")
        filter_text.add_mime_type("text/xml")
        dialog.add_filter(filter_text)
        dialog.set_current_folder('%s/data' % os.path.dirname(__file__))

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            self.xml_entry.set_text(dialog.get_filename())
        dialog.destroy()

    def list_models(self):
        self.models = []
        model_names = []
        for filename in glob.glob('asr/*.cfg'):
            try:
                items = config.read(filename)
                self.models.append(filename)
                if 'name' in items:
                    model_names.append(items['name'])
                else:
                    model_names.append(filename)
            except:
               pass
        return model_names

    def run(self):
        response = super(ModelSelector, self).run()
        if response != Gtk.ResponseType.OK:
            return None, None
        asr_model = self.models[self.model_chooser.get_active()]
        xml_filename = self.xml_entry.get_text()
        self.destroy()
        return xml_filename, asr_model