from gi.repository import Gtk
from gi.repository import Gdk

from pgconsole.config import cfg


class Settings(Gtk.Window):
    def __init__(self, parent):
        super(Settings, self).__init__()

        self._parent = parent

        self.set_title('Settings')
        self.set_modal(True)
        self.set_transient_for(parent.win)
        self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
        #self.set_border_width(10)
        self.connect("key_press_event", self.on_keypress)
        self.connect("destroy", self.on_destroy)

        self.tabs = Gtk.Notebook()
        self.add(self.tabs)

        ### Servers
        vbox = Gtk.VBox(spacing=10)
        vbox.set_border_width(10)
        self.tabs.append_page(vbox, Gtk.Label('Servers'))

        hbox = Gtk.HBox(spacing=10)
        vbox.pack_start(hbox, expand=True, fill=True, padding=0)
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
        sw.set_shadow_type(Gtk.ShadowType.IN)
        hbox.pack_start(sw, expand=True, fill=True, padding=0)
        tree = Gtk.TreeView()
        tree.set_headers_visible(False)
        sw.add(tree)
        tree.get_selection().set_mode(Gtk.SelectionMode.BROWSE)

        model = Gtk.ListStore(str, object)
        tree.set_model(model)
        column = Gtk.TreeViewColumn("Server", Gtk.CellRendererText(), text=0)
        tree.append_column(column)
        tree.get_selection().connect('changed', self.item_change)
        tree.set_size_request(100, -1)

        try:
            for server in cfg.servers.server:
                if str(server.name):
                    title = '%s (%s)' % (str(server.name), str(server.host))
                else:
                    title = str(server.host)
                model.append([title, server])
        except AttributeError:
            pass

        self.itemtree = tree

        vbox = Gtk.VBox(spacing=10)
        hbox.pack_start(vbox, expand=True, fill=True, padding=0)

        table = Gtk.Table(5, 2)
        table.set_row_spacings(4)
        table.set_col_spacings(10)
        vbox.pack_start(table, expand=True, fill=True, padding=0)

        label = Gtk.Label("Name:")
        label.set_alignment(0.0, 0.5)
        table.attach(label, 0, 1, 0, 1)
        entry = Gtk.Entry()
        table.attach(entry, 1, 2, 0, 1)
        self.entry_name = entry

        label = Gtk.Label("Host:")
        label.set_alignment(0.0, 0.5)
        table.attach(label, 0, 1, 1, 2)
        entry = Gtk.Entry()
        entry.set_text('127.0.0.1')
        table.attach(entry, 1, 2, 1, 2)
        self.entry_host = entry

        label = Gtk.Label("Port:")
        label.set_alignment(0.0, 0.5)
        table.attach(label, 0, 1, 2, 3)
        entry = Gtk.Entry()
        entry.set_text('5432')
        table.attach(entry, 1, 2, 2, 3)
        self.entry_port = entry

        label = Gtk.Label("User:")
        label.set_alignment(0.0, 0.5)
        table.attach(label, 0, 1, 3, 4)
        entry = Gtk.Entry()
        entry.set_text('postgres')
        table.attach(entry, 1, 2, 3, 4)
        self.entry_user = entry

        label = Gtk.Label("Password:")
        label.set_alignment(0.0, 0.5)
        table.attach(label, 0, 1, 4, 5)
        entry = Gtk.Entry()
        table.attach(entry, 1, 2, 4, 5)
        self.entry_password = entry

        hbox = Gtk.HBox()
        vbox.pack_start(hbox, expand=True, fill=True, padding=0)

        btn = Gtk.Button('Add')
        btn.connect('clicked', self.item_add)
        hbox.pack_start(btn, expand=True, fill=True, padding=0)
        btn = Gtk.Button('Save')
        btn.connect('clicked', self.item_save)
        hbox.pack_start(btn, expand=True, fill=True, padding=0)
        btn = Gtk.Button('Remove')
        btn.connect('clicked', self.item_remove)
        hbox.pack_start(btn, expand=True, fill=True, padding=0)

        ### Editor
        vbox = Gtk.VBox(spacing=10)
        vbox.set_border_width(10)
        self.tabs.append_page(vbox, Gtk.Label('Editor'))

        self.show_all()
        self.itemtree.grab_focus()



    def item_change(self, w):
        model, sel = self.itemtree.get_selection().get_selected_rows()
        if not sel:
            return
        el, = model.get(model.get_iter(sel[0]), 1)

        self.entry_name.set_text(str(el.name))
        self.entry_host.set_text(str(el.host))
        self.entry_port.set_text(str(el.port))
        self.entry_user.set_text(str(el.user))
        self.entry_password.set_text(str(el.password))


    def item_add(self, w):
        el = cfg.add_server(
            self.entry_name.get_text(),
            self.entry_host.get_text(),
            self.entry_port.get_text(),
            self.entry_user.get_text(),
            self.entry_password.get_text())
        if str(el.name):
            title = '%s (%s)' % (str(el.name), str(el.host))
        else:
            title = str(el.host)
        iter = self.itemtree.get_model().append([title, el])
        self.itemtree.get_selection().select_iter(iter)
        cfg.save()


    def item_save(self, w):
        model, sel = self.itemtree.get_selection().get_selected_rows()
        el = cfg.servers.server[sel[0][0]]
        el.name = self.entry_name.get_text()
        el.host = self.entry_host.get_text()
        el.port = self.entry_port.get_text()
        el.user = self.entry_user.get_text()
        el.password = self.entry_password.get_text()
        cfg.save()

        if str(el.name):
            title = '%s (%s)' % (str(el.name), str(el.host))
        else:
            title = str(el.host)
        model.set(model.get_iter(sel[0]), 0, title)


    def item_remove(self, w):
        model, sel = self.itemtree.get_selection().get_selected_rows()
        model.remove(model.get_iter(sel[0]))
        if model.get_iter_first():
            self.itemtree.get_selection().select_iter(model.get_iter_first())
        del cfg.servers.server[sel[0][0]]
        cfg.save()


    def on_keypress(self, w, event):
        keyname = Gdk.keyval_name(event.keyval)

        if keyname == 'Escape':
            self.destroy()
            return True
        return False


    def on_destroy(self, w):
        model, sel = self.itemtree.get_selection().get_selected_rows()
        if sel:
            sel = sel[0].get_indices()[0]
        else:
            sel = None
        self._parent.reload_server_list(sel)

