import psycopg2
import sqlalchemy
from qgis.PyQt.QtWidgets import QMessageBox
from xplordb.import_data import ImportData
from xplordb.import_ddl import ImportDDL

from openlog.datamodel.connection.postgres_utils import create_session
from openlog.gui.connection.connection_dialog import ConnectionDialog
from openlog.gui.connection.postgis_connection_widget import PostgisConnectionWidget


class XplordbConnectionDialog(ConnectionDialog):
    def __init__(self, parent=None) -> None:
        """
        QDialog to get an xplordb connection

        Args:
            parent: QWidget
        """
        super().__init__(parent)
        self.set_connection_widget(PostgisConnectionWidget())

        # translation

        self.setWindowTitle("Xplordb connection")

    def is_valid(self) -> bool:
        valid = super(XplordbConnectionDialog, self).is_valid()
        if valid:
            session, engine = create_session(
                self.connection_widget.get_connection_model()
            )

            try:
                data_importer = ImportData(session)
                data_importer.get_available_person_codes()
            except sqlalchemy.exc.SQLAlchemyError:
                ret = QMessageBox.warning(
                    self,
                    "Invalid database",
                    "xplordb schema not available.\n Do you want to install lite version ?",
                    QMessageBox.Ok | QMessageBox.Cancel,
                    QMessageBox.Ok,
                )
                session.rollback()
                if ret == QMessageBox.Ok:
                    valid = self._import_xplorddb_schema()
                else:
                    valid = False
        return valid

    def _import_xplorddb_schema(self) -> bool:
        conn = self.connection_widget.get_connection()
        result = True
        try:
            import_ddl_ = ImportDDL(
                host=conn.info.host,
                user=conn.info.user,
                password=conn.info.password,
                db=conn.info.dbname,
                port=int(conn.info.port),
            )
            import_ddl_.import_xplordb_schema(import_data=False, full_db=False)
        except psycopg2.Error as exc:
            result = False
            QMessageBox.warning(self, "Xplordb creation error", str(exc))
        return result
