# Copyright (c) 2001, 2003 by Intevation GmbH
# Authors:
# Martin Mueller <mmueller@intevation.de>
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.


"""Dialogs to manage database connections"""

import sys, traceback

from wxPython.wx import *

try:
    import psycopg
except ImportError:
    psycopg = None

from Thuban import _
from Thuban.UI.dialogs import NonModalDialog
from Thuban.Model.postgisdb import ConnectionError, PostGISConnection
from Thuban.Model.messages import DBCONN_ADDED, DBCONN_REMOVED
from messages import SESSION_REPLACED


ID_DB_ADD    = 9101
ID_DB_REMOVE = 9102

ID_DBCHOOSE_RETRIEVE = 9201
ID_DBCHOOSE_OK       = 9202
ID_DBCHOOSE_CANCEL   = 9203
ID_LB_DCLICK         = 9204


class ChooseDBTableDialog(wxDialog):

    def __init__(self, parent, session):
        wxDialog.__init__(self, parent, -1, _("Choose layer from database"),
                          style = wxDIALOG_MODAL|wxCAPTION)
        self.session = session
        self.dbconns = self.session.DBConnections()
        self.tables = []
        self.list_box_4 = wxListBox(self, -1)
        for i in range(len(self.dbconns)):
            self.list_box_4.Append(self.dbconns[i].BriefDescription())
        if self.list_box_4.GetCount() > 0:
            self.list_box_4.SetSelection(0, True)
        self.DB_CHOOSE_RETRIEVE = wxButton(self, ID_DBCHOOSE_RETRIEVE,
                                           _("Retrieve"))
        self.list_box_5 = wxListBox(self, ID_LB_DCLICK)
        self.DB_CHOOSE_OK = wxButton(self, ID_DBCHOOSE_OK, _("OK"))
        self.DB_CHOOSE_CANCEL = wxButton(self, ID_DBCHOOSE_CANCEL, _("Cancel"))
        self.__do_layout()

        EVT_BUTTON(self, ID_DBCHOOSE_OK, self.OnOK)
        EVT_BUTTON(self, ID_DBCHOOSE_CANCEL, self.OnCancel)
        EVT_BUTTON(self, ID_DBCHOOSE_RETRIEVE, self.OnRetrieve)
        EVT_LISTBOX_DCLICK(self, ID_LB_DCLICK, self.OnLBDClick)

    def __do_layout(self):
        grid_sizer_1 = wxFlexGridSizer(2, 1, 0, 0)
        grid_sizer_3 = wxFlexGridSizer(1, 2, 0, 0)
        grid_sizer_2 = wxFlexGridSizer(1, 3, 0, 0)
        sizer_4 = wxStaticBoxSizer(wxStaticBox(self, -1, _("Tables")),
                                   wxHORIZONTAL)
        grid_sizer_4 = wxFlexGridSizer(3, 1, 0, 0)
        sizer_3 = wxStaticBoxSizer(wxStaticBox(self, -1, _("Databases")),
                                   wxHORIZONTAL)
        sizer_3.Add(self.list_box_4, 0, wxEXPAND, 0)
        grid_sizer_2.Add(sizer_3, 1, wxEXPAND, 0)
        grid_sizer_4.Add(20, 80, 0, wxEXPAND, 0)
        grid_sizer_4.Add(self.DB_CHOOSE_RETRIEVE, 0, wxALL
                        |wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4)
        grid_sizer_4.Add(20, 80, 0, wxEXPAND, 0)
        grid_sizer_2.Add(grid_sizer_4, 1, wxEXPAND, 0)
        sizer_4.Add(self.list_box_5, 0, wxEXPAND, 0)
        grid_sizer_2.Add(sizer_4, 1, wxEXPAND, 0)
        grid_sizer_1.Add(grid_sizer_2, 1, wxEXPAND, 0)
        grid_sizer_3.Add(self.DB_CHOOSE_OK, 0, wxALL|wxALIGN_RIGHT, 4)
        grid_sizer_3.Add(self.DB_CHOOSE_CANCEL, 0, wxALL, 4)
        grid_sizer_1.Add(grid_sizer_3, 1, wxALL|wxALIGN_CENTER_HORIZONTAL, 4)
        self.SetAutoLayout(1)
        self.SetSizer(grid_sizer_1)
        grid_sizer_1.Fit(self)
        grid_sizer_1.SetSizeHints(self)
        self.Layout()

    def GetTable(self):
        i = self.list_box_5.GetSelection()
        if i >= 0:
            return self.selected_conn, self.tables[i]
        return None

    def OnRetrieve(self, event):
        i = self.list_box_4.GetSelection()
        if i >= 0:
            self.selected_conn = self.dbconns[i]
            self.tables = self.selected_conn.GeometryTables()
            self.list_box_5.Set(self.tables)

    def OnLBDClick(self, event):
        if self.list_box_5.GetSelection() >= 0:
            self.EndModal(wxID_OK)
            self.Show(False)

    def OnOK(self, event):
        self.EndModal(wxID_OK)
        self.Show(False)

    def OnCancel(self, event):
        self.EndModal(wxID_CANCEL)
        self.Show(False)


class DBDialog(wxDialog):

    """Dialog for the parameters of a database connection"""

    def __init__(self, parent, title, parameters, message = ""):
        """Initialize the dialog box.

        The parameters argument should be a dictionary containing known
        connection parameters.

        The optional message parameter will be displayed at the top of
        the dialog box and can be used to display error messages when
        using the dialog to ask for correct parameters when the
        connection can't be established.
        """
        wxDialog.__init__(self, parent, -1, title)

        top = wxBoxSizer(wxVERTICAL)

        if message:
            top.Add(wxStaticText(self, -1, message), 0,
                    wxALL|wxALIGN_CENTER_VERTICAL, 4)

        box = wxBoxSizer(wxHORIZONTAL)
        box.Add(wxStaticText(self, -1, _("Hostname:")), 0,
                wxALL|wxALIGN_CENTER_VERTICAL, 4)
        self.text_host = wxTextCtrl(self, -1, parameters.get("host", ""))
        box.Add(self.text_host, 2, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 4)
        box.Add(wxStaticText(self, -1, _("Port:")), 0,
                wxALL|wxALIGN_CENTER_VERTICAL, 4)
        self.text_port = wxTextCtrl(self, -1, parameters.get("port", ""))
        box.Add(self.text_port, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 4)
        top.Add(box, 0, wxEXPAND)

        box = wxBoxSizer(wxHORIZONTAL)
        box.Add(wxStaticText(self, -1, _("Database Name:")), 0,
                wxALL|wxALIGN_CENTER_VERTICAL, 4)
        self.text_dbname = wxTextCtrl(self, -1,
                                      parameters.get("dbname", ""))
        box.Add(self.text_dbname, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 4)
        top.Add(box, 0, wxEXPAND)

        box = wxBoxSizer(wxHORIZONTAL)
        box.Add(wxStaticText(self, -1, _("User:")), 0,
                wxALL|wxALIGN_CENTER_VERTICAL, 4)
        self.text_user = wxTextCtrl(self, -1,
                                    parameters.get("user", ""))
        box.Add(self.text_user, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND, 4)
        box.Add(wxStaticText(self, -1, _("Password:")), 0,
                wxALL|wxALIGN_CENTER_VERTICAL, 4)
        self.text_password = wxTextCtrl(self, -1,
                                        parameters.get("password", ""),
                                        style = wxTE_PASSWORD)
        box.Add(self.text_password, 1, wxALL|wxALIGN_CENTER_VERTICAL|wxEXPAND,
                4)
        top.Add(box, 0, wxEXPAND)

        buttons = wxBoxSizer(wxHORIZONTAL)
        button = wxButton(self, wxID_OK, _("OK"))
        buttons.Add(button, 0, wxALL, 4)
        button = wxButton(self, wxID_CANCEL, _("Cancel"))
        buttons.Add(button, 0, wxALL, 4)
        top.Add(buttons, 0, wxALIGN_RIGHT, 4)

        self.SetAutoLayout(1)
        self.SetSizer(top)
        top.Fit(self)
        top.SetSizeHints(self)

        EVT_BUTTON(self, wxID_OK, self.OnOK)
        EVT_BUTTON(self, wxID_CANCEL, self.OnCancel)

    def RunDialog(self):
        self.ShowModal()
        self.Destroy()
        return self.result

    def end_dialog(self, result):
        self.result = result
        if result is not None:
            self.EndModal(wxID_OK)
        else:
            self.EndModal(wxID_CANCEL)
        self.Show(False)

    def OnOK(self, event):
        result = {}
        for name in ("host", "port", "dbname", "user", "password"):
            result[name] = getattr(self, "text_" + name).GetValue()
        self.end_dialog(result)

    def OnCancel(self, event):
        self.end_dialog(None)



class DBFrame(NonModalDialog):

    """Databse connection management dialog"""

    def __init__(self, parent, name, session, *args, **kwds):
        kwds["style"] = wxICONIZE|wxCAPTION|wxMINIMIZE
        NonModalDialog.__init__(self, parent, name, "")
        self.session = session
        self.app = self.parent.application

        self.app.Subscribe(SESSION_REPLACED, self.session_replaced)
        self.subscribe_session()

        self.DB_ListBox = wxListBox(self, -1,
                              style=wxLB_SINGLE|wxLB_HSCROLL|wxLB_ALWAYS_SB)
        self.DB_Add = wxButton(self, ID_DB_ADD, _("Add"))
        self.DB_Remove = wxButton(self, ID_DB_REMOVE, _("Remove"))
        self.DB_CLOSE = wxButton(self, wxID_CLOSE, _("Close"))
        self.__set_properties()
        self.__do_layout()
        EVT_BUTTON(self, ID_DB_ADD, self.OnAdd)
        EVT_BUTTON(self, ID_DB_REMOVE, self.OnRemove)
        EVT_BUTTON(self, wxID_CLOSE, self.OnClose)

        self.conns_changed()

    def __set_properties(self):
        self.SetTitle(_("Database Management"))
        self.DB_ListBox.SetSize((200, 157))

    def __do_layout(self):
        top = wxBoxSizer(wxVERTICAL)

        box = wxBoxSizer(wxHORIZONTAL)

        box.Add(self.DB_ListBox, 1, wxALL|wxEXPAND
                |wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 4)

        buttons = wxBoxSizer(wxVERTICAL)
        buttons.Add(self.DB_Add, 0, wxALL, 4)
        buttons.Add(self.DB_Remove, 0, wxALL, 4)

        box.Add(buttons, 0, wxEXPAND)
        top.Add(box, 1, wxEXPAND)

        buttons = wxBoxSizer(wxHORIZONTAL)
        buttons.Add(self.DB_CLOSE, 1, wxALL|wxALIGN_RIGHT, 4)
        top.Add(buttons, 0, wxALIGN_RIGHT)

        self.SetAutoLayout(1)
        self.SetSizer(top)
        top.Fit(self)
        top.SetSizeHints(self)

    def subscribe_session(self):
        """Internal: Subscribe to some session messages"""
        self.session.Subscribe(DBCONN_ADDED, self.conns_changed)
        self.session.Subscribe(DBCONN_REMOVED, self.conns_changed)

    def unsubscribe_session(self):
        """Internal: Subscribe from messages subscribe in subscribe_session"""
        self.session.Subscribe(DBCONN_ADDED, self.conns_changed)
        self.session.Subscribe(DBCONN_REMOVED, self.conns_changed)

    def session_replaced(self, *args):
        """Internal: resubscribe the session messages

        This method is a subscriber for the application's
        SESSION_REPLACED messages.
        """
        self.unsubscribe_session()
        self.session = self.app.Session()
        self.subscribe_session()
        self.conns_changed()

    def conns_changed(self, *args):
        """Internal: update the db connection list box

        Subscribed to the DBCONN_ADDED and DBCONN_REMOVED messages.
        """
        self.DB_ListBox.Clear()
        for conn in self.session.DBConnections():
            self.DB_ListBox.Append(conn.BriefDescription(), conn)

    def OnClose(self, event):
        self.unsubscribe_session()
        self.app.Unsubscribe(SESSION_REPLACED, self.session_replaced)
        NonModalDialog.OnClose(self, event)

    def RunMessageBox(self, title, text, flags = wxOK | wxICON_INFORMATION):
        """Run a modal message box with the given text, title and flags
        and return the result"""
        dlg = wxMessageDialog(self, text, title, flags)
        dlg.CenterOnParent()
        result = dlg.ShowModal()
        dlg.Destroy()
        return result

    def OnAdd(self, event):
        message = ""
        parameters = {}
        while 1:
            dialog = DBDialog(self, _("Add Database"), parameters, message)
            parameters = dialog.RunDialog()
            if parameters is not None:
                for conn in self.session.DBConnections():
                    if conn.MatchesParameters(parameters):
                        self.RunMessageBox(_("Add Database"),
                                         _("Connection '%s' already exists")
                                           % conn.BriefDescription())
                        break
                else:
                    try:
                        conn = PostGISConnection(**parameters)
                    except ConnectionError, val:
                        message = str(val)
                    else:
                        self.session.AddDBConnection(conn)
                        break
            else:
                break

    def OnRemove(self, event):
        i = self.DB_ListBox.GetSelection()
        if i >= 0:
            conn = self.DB_ListBox.GetClientData(i)
            if self.session.CanRemoveDBConnection(conn):
                self.session.RemoveDBConnection(conn)
            else:
                self.RunMessageBox(_("Remove Database Connection"),
                                   _("The connection %s\nis still in use")
                                   % conn.BriefDescription())
