# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name                 : Mascaret
Description          : Pre and Postprocessing for Mascaret for QGIS
Date                 : Aprile, 2025
copyright            : (C) 2025 by Artelia
email                :
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from lib.db import MasObject as Maso
from psycopg2 import sql


class ClassUpdate306:

    def __init__(self, check_tab):
        self.mdb = check_tab.mdb
        self.mgis = check_tab.mgis
        self.cht = check_tab

    def update306(self):
        """add new table law and convert"""
        self.update_tab_306()
        self.add_trigger_update_306()

    def update_tab_306(self):

        update_stmt = {
            "branchs": 
                "UPDATE {schema}.branchs SET active = TRUE WHERE active IS NULL;",
            "profiles": 
                "UPDATE {schema}.profiles SET active = TRUE WHERE active IS NULL;",
            "tracer_lateral_inflows":
                "UPDATE {schema}.tracer_lateral_inflows SET active WHERE active IS NULL;",
            "lateral_weirs":
                "UPDATE {schema}.lateral_weirs SET active = TRUE WHERE active IS NULL;",
            "lateral_inflows":
                "UPDATE {schema}.lateral_inflows SET active = TRUE WHERE active IS NULL;",
            "hydraulic_head":
                "UPDATE {schema}.hydraulic_head SET active = TRUE WHERE active IS NULL;",
            "weirs": 
                "UPDATE {schema}.weirs SET active = TRUE WHERE active IS NULL;",
            "extremities": 
                "UPDATE {schema}.extremities SET active = TRUE WHERE active IS NULL;",
            "links": 
                "UPDATE {schema}.links SET active = TRUE WHERE active IS NULL;",
            "basins": 
                "UPDATE {schema}.basins SET active = TRUE WHERE active IS NULL;",
            "outputs": 
                "UPDATE {schema}.outputs SET active = TRUE WHERE active IS NULL;",
            "flood_marks": 
                "UPDATE {schema}.flood_marks SET active = TRUE WHERE active IS NULL;",
            "laws": 
                "UPDATE {schema}.laws SET active = TRUE WHERE active IS NULL;",
        }
        try:
            list_tab = list(update_stmt.keys())
            txt = ""
            for tab in list_tab:
                tab_id = sql.Identifier(tab)
                txt += sql.SQL(
                    "ALTER TABLE {schema}.{0} ALTER COLUMN active SET DEFAULT TRUE;"
                ).format(tab_id)
                txt += "\n"
                txt += update_stmt[tab]
                txt += "\n"
                txt += sql.SQL("ALTER TABLE {schema}.{0} ALTER COLUMN active SET NOT NULL;").format(
                    tab_id
                )
                txt += "\n"
                return True
        except Exception as e:
            self.mgis.add_info("Error update_tab_306: {}".format(str(e)))
            return False

    def add_trigger_update_306(self):
        """
        add trigger and fct for 3.0.6 version
        trigger :
        'pg_delete_visu_flood_marks',
        'pg_create_calcul_abscisse_point_flood'
        :return:
        """
        try:
            self.update_fct_calc_abs()
            self.mdb.add_fct_for_visu()

            qry = "DROP TRIGGER IF EXISTS branchs_chstate_active ON {schema}.branchs;\n"
            qry += "DROP TRIGGER IF EXISTS basins_chstate_active ON {schema}.basins;\n"
            qry += (
                "DROP TRIGGER IF EXISTS flood_marks_calcul_abscisse " "ON {schema}.flood_marks;\n"
            )
            qry += (
                "DROP TRIGGER IF EXISTS flood_marks_calcul_abscisse_flood "
                "ON {schema}.flood_marks;\n"
            )
            qry += (
                "DROP TRIGGER IF EXISTS flood_marks_delete_point_flood "
                "ON {schema}.flood_marks;\n"
            )
            qry += "\n"
            cl = Maso.class_fct_psql()
            qry += cl.pg_chstate_branch()
            qry += "\n"
            qry += (
                "CREATE TRIGGER branchs_chstate_active\n" " AFTER UPDATE\n  ON {schema}.branchs\n"
            )
            qry += (
                " FOR EACH ROW\n"
                "WHEN (OLD.active IS DISTINCT FROM NEW.active)\n"
                "EXECUTE PROCEDURE chstate_branch();\n"
            )
            qry += "\n"
            qry += cl.pg_chstate_basin()
            qry += "\n"
            qry += "CREATE TRIGGER basins_chstate_active\n" " AFTER UPDATE\n  ON {schema}.basins\n"
            qry += (
                " FOR EACH ROW\n"
                "WHEN (OLD.active IS DISTINCT FROM NEW.active)\n"
                "EXECUTE PROCEDURE chstate_basin();\n"
            )
            qry += "\n"
            cl = Maso.flood_marks()
            cl.schema = self.mdb.SCHEMA
            qry += cl.pg_clear_tab()
            qry += "\n"
            qry += cl.pg_calcul_abscisse_flood()
            qry += "\n"
            self.mdb.run_query(qry, schema=True)

            return True
        except Exception as e:
            self.mgis.add_info("Error add_trigger_update_306: {}".format(str(e)))
            return False

    def update_fct_calc_abs(self):
        try:
            lst_fct = [
                "public.update_abscisse_branch(_tbl_branchs regclass)",
                "public.update_abscisse_point" "(_tbl regclass, _tbl_branchs regclass)",
                "public.update_abscisse_profil" "(_tbl regclass, _tbl_branchs regclass)",
                "public.abscisse_branch" "(_tbl_branchs regclass, id_branch integer)",
                "public.abscisse_point" "(_tbl regclass, _tbl_branchs regclass, id_point integer)",
                "public.abscisse_profil" "(_tbl regclass, _tbl_branchs regclass, id_prof integer)",
            ]
            qry = ""
            for fct in lst_fct:
                qry += "DROP FUNCTION IF EXISTS {};\n".format(fct)
            self.mdb.run_query(qry)
            self.add_fct_for_update_pk_old()
            return True
        except Exception as e:
            self.mgis.add_info("Error update_fct_calc_abs: {}".format(str(e)))
            return False

    def add_fct_for_update_pk_old(self):
        """add fct psql to compute abscissa"""
        cl = Maso.class_fct_psql()
        lfct = [
            cl.pg_abscisse_profil(self.mdb.SCHEMA),
            cl.pg_all_profil(self.mdb.SCHEMA),
            cl.pg_abscisse_point(self.mdb.SCHEMA),
            cl.pg_all_point(self.mdb.SCHEMA),
        ]
        qry = ""
        for sqlf in lfct:
            qry += sqlf()
            qry += "\n"
        self.mdb.run_query(qry)
