DROP FUNCTION IF EXISTS func_refresh_view_materialized(text);

CREATE OR REPLACE FUNCTION func_refresh_view_materialized(v_input_vm text)
RETURNS text AS $$
DECLARE v_text_value text DEFAULT '';
BEGIN
    BEGIN
		
		IF ((SELECT last_request_execution FROM refresh_view_m WHERE name_view = v_input_vm) > (SELECT last_executed FROM refresh_view_m WHERE name_view = v_input_vm) 
			OR (EXTRACT(EPOCH FROM(NOW() - (SELECT last_executed FROM refresh_view_m WHERE name_view = v_input_vm))) > (SELECT refresh_time_s FROM refresh_view_m WHERE name_view = v_input_vm))
		   ) THEN
  			
			IF v_input_vm = 'entrega_resultados_view_m' THEN
				REFRESH MATERIALIZED VIEW CONCURRENTLY entrega_resultados_view_m;
			END IF;
			
			IF v_input_vm = 'asignacion_cita_view_m' THEN
				REFRESH MATERIALIZED VIEW CONCURRENTLY asignacion_cita_view_m;
			END IF;
			
			IF v_input_vm = 'confirmacion_cita_view_m' THEN
				REFRESH MATERIALIZED VIEW CONCURRENTLY confirmacion_cita_view_m;
			END IF;
			
			UPDATE refresh_view_m SET
				last_executed = NOW()
			WHERE	name_view = v_input_vm;
			
			v_text_value := 'Vista ' || v_input_vm || ' refrescada. :) ';
		ELSE
			v_text_value := 'NO se refrescó la vista ' || v_input_vm || ' :| ';
  		END IF;
		
	EXCEPTION WHEN OTHERS THEN
		RAISE EXCEPTION 'Error al refrescar la vista "%".  :( ', v_input_vm;
	RETURN 'Error al refrescar la vista "%". :( ',v_input_vm;
		   
    END;
RETURN v_text_value;
END;
$$ LANGUAGE plpgsql;