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

class ModelSelector(Gtk.Dialog):
    def __init__(self, xml_filename = '', asr_model = ''):
        super(ModelSelector, self).__init__()
        self.options = {'xml_filename': xml_filename, 'asr_model': asr_model, 'osc_host': '127.0.0.1', 'osc_port': '1234'}
        self.load_options()

        self.set_title('Configuration')
        self.set_border_width(10)
        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, 5)
        xml_entry = Gtk.Entry()
        xml_entry.set_text(self.options['xml_filename'])
        xml_entry.set_width_chars(len(self.options['xml_filename']))
        self.xml_entry = xml_entry
        xml_box.pack_start(xml_entry, True, True, 5)
        xml_button = Gtk.Button("Choose...")
        xml_button.connect('clicked', self.show_filechooser)
        xml_box.pack_start(xml_button, False, False, 5)

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

        model_box = Gtk.HBox()
        model_box.pack_start(Gtk.Label('ASR model:'), False, False, 5)
        model_chooser = Gtk.ComboBoxText()
        model_chooser.set_entry_text_column(0)
        target_index = 0
        for i, model in enumerate(self.list_models()):
            model_chooser.append_text(model)
            if self.options['asr_model'] == self.models[i]:
                target_index = i
        model_chooser.set_active(target_index)
        self.model_chooser = model_chooser
        model_box.pack_start(model_chooser, True, True, 5)

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

        osc_box = Gtk.HBox()
        osc_box.pack_start(Gtk.Label('OSC host:'), False, False, 5)
        osc_host = Gtk.Entry()
        osc_host.set_text(self.options['osc_host'])
        osc_host.set_width_chars(len(osc_host.get_text()))
        self.osc_host = osc_host
        osc_box.pack_start(osc_host, True, True, 5)
        osc_box.pack_start(Gtk.Label('Port:'), False, False, 5)
        osc_port = Gtk.Entry()
        osc_port.set_text(self.options['osc_port'])
        osc_port.set_width_chars(len(osc_port.get_text()))
        self.osc_port = osc_port
        osc_box.pack_start(osc_port, True, True, 5)

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

        self.xml_entry.set_activates_default(True)
        okButton = self.get_widget_for_response(response_id=Gtk.ResponseType.OK)
        okButton.set_can_default(True)
        okButton.grab_default()
        okButton.grab_focus()

        self.show_all()

    def save_options(self):
        try:
            with open('.options.txt', 'w') as fp:
                for key, value in self.options.items():
                    print >>fp, '%s: %s' % (key, str(value))
        except:
            print 'Warning: could not save options'

    def load_options(self):
        try:
            with open('.options.txt') as fp:
                for line in fp:
                    line = line.strip()
                    found = re.search('^([^:]*):(.*)', line)
                    if found:
                        key = found.group(1).strip()
                        value = found.group(2).strip()
                        self.options[key] = value
        except:
            print 'Warning: could not load options'

    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__) or '.'))

        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, None, None
        self.options['asr_model'] = self.models[self.model_chooser.get_active()]
        self.options['xml_filename'] = self.xml_entry.get_text()
        self.options['osc_host'] = self.osc_host.get_text()
        self.options['osc_port'] = self.osc_port.get_text()
        self.save_options()
        self.destroy()
        return self.options['xml_filename'], self.options['asr_model'], self.options['osc_host'], self.options['osc_port']