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

CREATE TEMP TABLE w_dbsetup AS
    WITH flatSeries as (
    SELECT 
    	oid,
    	CASE WHEN serie_id != '{}' THEN split_part(split_part(unnest(string_to_array(serie_id, '|')), 'pos":', 2), ',', 1)::bigint END as position,
    	CASE WHEN serie_id != '{}' THEN replace(split_part(unnest(string_to_array(serie_id, '|')), 'id":', 2), '}', '')::bigint END as id
    FROM pmsi.t_indicateur_serie
    ORDER BY oid, position
		),

		flatCodes as (SELECT 
    flatSeries.oid,
    array_agg(position || ':' || t_indicateur_serie.code) as codes
		FROM flatSeries
		LEFT JOIN pmsi.t_indicateur_serie on t_indicateur_serie.oid = id
		GROUP BY 1)

		SELECT
    t_indicateur_serie.code,
    coalesce(t_indicateurs.code, '') as indicateur_code,
    t_indicateur_serie.name,
    t_indicateur_serie.color,
    t_indicateur_serie.formula,
    t_indicateur_serie.calc,
    t_indicateur_serie.total,
    t_indicateur_serie.format,
    case when array_agg(DISTINCT t_indicateur_condition.external_code2) = ARRAY[null] then ARRAY[]::text[] else array_agg(DISTINCT t_indicateur_condition.external_code2) end  as external_code2,
    		CASE WHEN flatCodes.codes = ARRAY[null] THEN '{}'::text[] ELSE flatCodes.codes::text[] END as serie_code
		FROM pmsi.t_indicateur_serie
		LEFT JOIN pmsi.t_indicateurs ON t_indicateurs.oid = indicateur_id
		LEFT JOIN pmsi.t_indicateur_condition ON ARRAY[t_indicateur_condition.oid] <@ t_indicateur_serie.condition_id
		LEFT JOIN flatCodes on flatCodes.oid = t_indicateur_serie.oid
		GROUP BY 1,2,3,4,5,6,7,8, flatCodes.codes
		ORDER BY 2,1 LIMIT 0
;

-- 2/3 : Peuplement de la table temporaire
INSERT INTO w_dbsetup(
    code,
    indicateur_code,
    name,
    color,
    formula,
    calc,
    total,
    format,
    external_code2,
    serie_code
)
VALUES
('CTI_CAT2AAMBU', 'CTI-CA0NT2A', 'CAT2A Ambulatoire', '#011b43', '', 'f', 'f', '0.00', '{""}', '{}'),
('CTI_CAT2AHOSP', 'CTIESS_CAT2AHOSP', 'CAT2A Hospitalisés', '#07689F', '', 'f', 'f', '0.00', '{""}', '{}'),
('CTI_CAT2AAMBUMOY', 'CTIESS_CAT2AMOYAMBU', 'CAT2A Ambulatoire Moyen', '#011b43', '', 'f', 'f', '0.00', '{""}', '{}'),
('CTI_CAT2AHOSPMOY', 'CTIESS_CAT2AMOYHOSP', 'CAT2A Hospitalisés Moyen', '#07689F', '', 'f', 'f', '0.00', '{""}', '{}'),
('CTI_DMSHOSP', 'CTIESS_DMSHOSP', 'DMS Hospitalises', '#07689F', '', 'f', 'f', '0.00', '{""}', '{}'),
('CTI_GHM80', 'CTIESS_NBGHM_80N', 'GHM couvrant 80% de l''activité', '#07689F', '', 'f', 'f', '', '{""}', '{}'),
('CTI_NBSEJGR', 'CTIESS_NBSEJGNEX', 'Nombre de séjours groupés non expédiés', '#07689F', '', 'f', 'f', '', '{""}', '{}'),
('CTI_NBSEJ', 'CTI_NB_SEJ', 'Nombre de séjours', '#07689F', '', 'f', 'f', '', '{""}', '{}'),
('CTI_NBSEJFEMMES', 'CTI_NB_SEJ', 'Nombre de séjours Femmes', '#07689F', '', 'f', 'f', '', '{"CTI_SEXE#DT#2"}', '{}'),
('CTI_NBSEJHOMMES', 'CTI_NB_SEJ', 'Nombre de séjours Hommes', '#011b43', '', 'f', 'f', '', '{"CTI_SEXE#DT#1"}', '{}')
;

-- 3/3 : Màj de la table iCTI
SELECT pmsi.cti_reorganize_indicateur_condition();

TRUNCATE pmsi.t_indicateur_serie;

INSERT INTO pmsi.t_indicateur_serie(indicateur_id, condition_id, name, color, formula, calc, serie_id, total, format, code)
	SELECT
		coalesce(t_indicateurs.oid, 0),
		case when array_agg(DISTINCT t_indicateur_condition.oid) = ARRAY[NULL]::bigint[] then ARRAY[]::bigint[] else array_agg(DISTINCT t_indicateur_condition.oid) end,
		w_dbsetup.name,
		w_dbsetup.color,
		w_dbsetup.formula,
		w_dbsetup.calc,
		case when array_agg(DISTINCT rec.oid) = ARRAY[NULL]::bigint[] then ARRAY[]::bigint[] else array_agg(DISTINCT rec.oid) end,
		w_dbsetup.total,
		w_dbsetup.format,
		w_dbsetup.code
FROM w_dbsetup
LEFT JOIN pmsi.t_indicateurs ON t_indicateurs.code = w_dbsetup.indicateur_code
LEFT JOIN pmsi.t_indicateur_condition ON ARRAY[t_indicateur_condition.external_code2] <@ w_dbsetup.external_code2
LEFT JOIN pmsi.t_indicateur_serie as rec ON ARRAY[rec.code] <@ w_dbsetup.serie_code
GROUP BY 1,3,4,5,6,8,9,10
;

WITH series_id as (
SELECT
		w_dbsetup.code,
		split_part(unnest(w_dbsetup.serie_code), ':', 1) as pos,
		split_part(unnest(w_dbsetup.serie_code), ':', 2) as serie_code
FROM w_dbsetup
), 

full_series as (
SELECT
	series_id.code,
	coalesce(string_agg('{"pos": ' || pos || ', "id": ' || t_indicateur_serie.oid || '}', '|'), '') as serie_id
FROM series_id
LEFT JOIN pmsi.t_indicateur_serie ON t_indicateur_serie.code = serie_code
GROUP BY 1
)


UPDATE pmsi.t_indicateur_serie SET
	serie_id = CASE WHEN full_series.serie_id IS NULL THEN '' ELSE full_series.serie_id END
	FROM w_dbsetup
	LEFT JOIN full_series ON full_series.code = w_dbsetup.code
WHERE t_indicateur_serie.code = w_dbsetup.code
;