-- Copyright 2010, Intevation GmbH, Germany, <info@intevation.de>
--
-- This file is part of FGSK.
--
-- FGSK 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.
--
-- FGSK is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-- FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
-- License for more details.
--
-- You should have received a copy of the GNU General Public
-- License along with FGSK. If not, see <http://www.gnu.org/licenses/>.
--
-- FGSK has been developed on behalf of the
-- Landesamt fuer Umwelt und Geologie Mecklenburg Vorpommern (LUNG-MV)
-- by Intevation GmbH. 
-- biota Institut fuer oekologische Forschung und Planung GmbH has provided
-- the functional background.
--
-- Authors:
-- Tim Englich <tim.englich@intevation.de>
-- Ingo Weinzierl <ingo.weinzierl@intevation.de>

BEGIN;
CREATE OR REPLACE FUNCTION update_gewaessersubtyp_kartierabschnitt_func()
RETURNS TRIGGER AS
$$
DECLARE
BEGIN

    RAISE DEBUG '%: TABLE NAME = %', TG_OP, TG_TABLE_NAME;
    IF (TG_OP = 'UPDATE') THEN
        IF (TG_TABLE_NAME = 'kartierabschnitt_hat_gewaessersubtyp') THEN
            IF (NEW.gewaessersubtyp_id IS NULL OR
                NEW.gewaessersubtyp_id = OLD.gewaessersubtyp_id) THEN
                RAISE DEBUG 'Daten unveraendert keine berechnung notwendig';
                RETURN NEW;
            END IF;
        END IF;
    END IF;

    PERFORM calculate_points_sohlenstruktur_func(NEW.kartierabschnitt_id);
    RETURN NEW;

END;
$$ LANGUAGE plpgsql;

--
-- remove existing triggers before creating new ones
--
DROP TRIGGER IF EXISTS update_gewaessersubtyp_kartierabschnitt
ON kartierabschnitt_hat_gewaessersubtyp;


--
-- necessary trigger for table kartierabschnitt
--
CREATE TRIGGER update_gewaessersubtyp_kartierabschnitt
AFTER INSERT OR UPDATE
    ON kartierabschnitt_hat_gewaessersubtyp
    FOR EACH ROW EXECUTE PROCEDURE
        update_gewaessersubtyp_kartierabschnitt_func();
        
-- END TRANSACTION
END;