"""Adds a trigger to notify QGIS on changes."""

from alembic import op
from xplan_tools.settings import get_settings

revision = "3715fd158e35"
down_revision = None
branch_labels = None
depends_on = None


schema = get_settings().db_schema or "public"


def upgrade():
    """Upgrade schema."""
    op.execute(f"""
        DROP TRIGGER IF EXISTS trg_notify_qgis ON {schema}.coretable;
        DROP FUNCTION IF EXISTS {schema}.fn_notify_qgis();

        CREATE OR REPLACE FUNCTION {schema}.xmas_notify_qgis() RETURNS trigger AS $$
        BEGIN
            PERFORM pg_notify('qgis', concat('xmas_plugin/refresh_', NEW.geometry_type));
            RETURN NEW;
        END;
        $$ LANGUAGE plpgsql;

        CREATE TRIGGER xmas_notify_qgis
        AFTER INSERT OR UPDATE ON {schema}.coretable
        FOR EACH ROW
        EXECUTE FUNCTION {schema}.xmas_notify_qgis();
    """)


def downgrade():
    """Downgrade schema."""
    op.execute(f"""
        DROP TRIGGER IF EXISTS xmas_notify_qgis ON {schema}.coretable;
        DROP FUNCTION IF EXISTS {schema}.xmas_notify_qgis();
    """)
