#ifdef CAD // 22-05-1998 KTH
/*
 * $Revision$
 * $Id$
 */

CREATE OR REPLACE PACKAGE cad AS
    PROCEDURE refreshlegenda (themakey IN NUMBER, reinit IN NUMBER);
END cad;
/
CREATE OR REPLACE PACKAGE BODY cad
AS
    PROCEDURE refreshlegenda (themakey IN NUMBER, reinit IN NUMBER)
    AS
        vname           cad_thema.cad_thema_view%TYPE;
        lkey            cad_thema.cad_legenda_key%TYPE;
        tomschrijving   cad_thema.cad_thema_omschrijving%TYPE;
        sql_stmt        VARCHAR2 (1000);
        newlegenda      BOOLEAN := FALSE;
    BEGIN
        BEGIN
            -- Welke domein en welke legenda?
            SELECT cad_thema_view, cad_legenda_key, cad_thema_omschrijving
              INTO vname, lkey, tomschrijving
              FROM cad_thema
             WHERE cad_thema_key = themakey;
        EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
                newlegenda := TRUE;
        END;


        IF newlegenda OR lkey IS NULL
        THEN
            -- nieuwe legenda
            INSERT INTO cad_legenda (cad_legenda_omschrijving, cad_legenda_discreet)
                VALUES (SUBSTR(tomschrijving, 1, 32), 1)
             RETURNING cad_legenda_key
                  INTO lkey;

            -- gebruiken bij dit thema
            UPDATE cad_thema
               SET cad_legenda_key = lkey
             WHERE cad_thema_key = themakey;
        ELSE
            -- bestaande legenda, eventueel wissen
            IF reinit = 1
            THEN
                DELETE FROM cad_legendawaarde WHERE cad_legenda_key = lkey;
            END IF;
        END IF;



        sql_stmt :=
            'INSERT INTO cad_legendawaarde (cad_legenda_key, cad_legendawaarde_value, cad_legendawaarde_rgb, cad_legendawaarde_omschr) '
            || 'SELECT DISTINCT '
            || TO_CHAR (lkey)
            || ',  waarde, '
            || 'TO_CHAR(DBMS_UTILITY.get_hash_value (waarde, 0, POWER (2, 24)), ''0XXXXX'')'
            || ', REPLACE(waarde, ''*'', '''')'
            || ' FROM '
            || vname -- er zit een constraint op cad_thema.cad_thema_view dus relatief SQL-injection safe
            || ' thv WHERE REPLACE (waarde, ''*'', '''') IS NOT NULL'
            || ' AND NOT EXISTS '
            || ' (SELECT cl.cad_legendawaarde_value FROM cad_legendawaarde cl WHERE cl.cad_legendawaarde_value = thv.waarde AND cl.cad_legenda_key = '
            || TO_CHAR (lkey)
            || ')';

        DBMS_OUTPUT.put_line (sql_stmt);

        EXECUTE IMMEDIATE sql_stmt;
    END;
END cad;
/
REGISTERRUN('$Id$')

#endif // CAD

