-- 1/3 : Création de la table temporaire
DROP TABLE IF EXISTS w_dbsetup
;

CREATE TEMP TABLE w_dbsetup AS
    SELECT
    	t_classes_sections.code AS section_code, 
    	t_etat_sejour.code as to_code, 
    	t_listes_tables.code as table_code, 
    	t_classes.sequence as classe_sequence 
    FROM 
    	activite.t_classes_sections_elements, 
    	activite.t_classes_sections, 
    	activite.t_classes, 
    	activite.t_listes_tables, 
    	activite.t_etat_sejour
    WHERE 
    	t_classes_sections_elements.section_id = t_classes_sections.oid
    	AND t_classes_sections.classe_id = t_classes.oid 
    	AND t_classes.is_cti = '1' 
    	AND table_id = t_listes_tables.oid
    	AND t_listes_tables.code = 'ETATSEJOUR'
    	AND t_classes_sections_elements.to_id = t_etat_sejour.oid
    ORDER BY t_classes.sequence, t_classes_sections.code, t_etat_sejour.code LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    section_code,
    to_code,
    table_code,
    classe_sequence
)
VALUES
('S1', '0', 'ETATSEJOUR', 10),
('S2', '1', 'ETATSEJOUR', 10),
('S2', '2', 'ETATSEJOUR', 10),
('S3', '3', 'ETATSEJOUR', 10),
('S4', '4', 'ETATSEJOUR', 10),
('S4', '5', 'ETATSEJOUR', 10),
('S5', '6', 'ETATSEJOUR', 10),
('S6', '7', 'ETATSEJOUR', 10),
('S6', '8', 'ETATSEJOUR', 10),
('S7', '9', 'ETATSEJOUR', 10),
('S8', 'A', 'ETATSEJOUR', 10),
('S8', 'C', 'ETATSEJOUR', 10),
('S8', 'R', 'ETATSEJOUR', 10),
('S1', '0', 'ETATSEJOUR', 11),
('S1', '9', 'ETATSEJOUR', 11),
('S2', '1', 'ETATSEJOUR', 11),
('S2', '2', 'ETATSEJOUR', 11),
('S3', '3', 'ETATSEJOUR', 11),
('S3', '4', 'ETATSEJOUR', 11),
('S3', '5', 'ETATSEJOUR', 11),
('S4', '6', 'ETATSEJOUR', 11),
('S5', '7', 'ETATSEJOUR', 11),
('S5', '8', 'ETATSEJOUR', 11),
('S6', 'A', 'ETATSEJOUR', 11),
('S6', 'C', 'ETATSEJOUR', 11),
('S6', 'R', 'ETATSEJOUR', 11)
;

-- 3/3 : Màj de la table iCTI
INSERT INTO activite.t_classes_sections_elements(section_id, to_id)     
SELECT 
	t_classes_sections.oid, 
	t_etat_sejour.oid 
FROM 
	w_dbsetup, 
	activite.t_listes_tables, 
	activite.t_classes, 
	activite.t_classes_sections, 
	activite.t_etat_sejour   
WHERE 
	w_dbsetup.table_code = t_listes_tables.code       
	AND t_classes.table_id = t_listes_tables.oid   
	AND t_classes_sections.classe_id = t_classes.oid   
	AND w_dbsetup.section_code = t_classes_sections.code
	AND w_dbsetup.classe_sequence = t_classes.sequence
	AND w_dbsetup.to_code = t_etat_sejour.code
	AND t_classes_sections.oid::text || '-'::text || t_etat_sejour.oid::text NOT IN (SELECT section_id::text || '-'::text || to_id::text FROM activite.t_classes_sections_elements);

SELECT * FROM activite.cti_update_schema_classes('ETATSEJOUR');