/**
 * @author sbarthon
 * @date 06/04/2022
 * @version 1.0.0
 * @project SIEau
 * @function f_calc_premier_index
 */
# --- !Ups

drop function f_calc_premier_index(p_idCapteur INTEGER, p_dateDebut TIMESTAMP with time zone) ;

create function f_calc_premier_index(p_idCapteur INTEGER, p_dateDebut TIMESTAMP with time zone)
returns REAL
language plpgsql
as $$
DECLARE
	v_dateIndex1 TIMESTAMP with time zone;;
	v_index1 REAL;;

BEGIN
	-- Premier index connu
	p_dateDebut = date_trunc('day', p_dateDebut) + INTERVAL '1 day';;
	raise notice 'f_calc_premier_index date début: %', p_dateDebut;;

	SELECT dateMesure, mesure INTO v_dateIndex1, v_index1
	FROM MAT_CHRONIQUES
	WHERE idmateriel=p_idCapteur AND typemesure=2 AND dateMesure<p_dateDebut
	ORDER BY dateMesure DESC LIMIT 1;;

	IF v_index1 IS NULL THEN
		SELECT dateMesure, mesure INTO v_dateIndex1, v_index1
		FROM MAT_CHRONIQUES
		WHERE idmateriel=p_idCapteur AND typemesure=2 AND dateMesure>=p_dateDebut AND datemesure<p_dateDebut + INTERVAL '1 year'
		ORDER BY dateMesure ASC LIMIT 1;;
	END IF;;
	raise notice 'f_calc_premier_index  : % - %', v_dateIndex1, v_index1;;

	RETURN v_index1;;
END;;
$$
;

# --- !Downs