------------------------------------------
------------- DROP TRIGGERS --------------
------------------------------------------

DROP TRIGGER IF EXISTS group_modified ON groups;

------------------------------------------
------------ DROP FUNCTIONS --------------
------------------------------------------
DROP FUNCTION IF EXISTS group_update();

------------------------------------------
------------ CREATE FUNCTIONS ------------
------------------------------------------

CREATE OR REPLACE FUNCTION group_update()
  RETURNS trigger AS
$BODY$
DECLARE
	thisgroup RECORD;
	forstart INTEGER;
BEGIN
	RAISE NOTICE 'OLD is %',OLD.max_screens;
	RAISE NOTICE 'NEW is %',NEW.max_screens;
	IF OLD.max_screens > NEW.max_screens THEN
		DELETE FROM screen_events WHERE screen_detail_id IN (SELECT id FROM screen_details WHERE screen_id IN ( SELECT id FROM screens WHERE "order" > NEW.max_screens AND group_id = new.id));
		DELETE FROM screen_details WHERE screen_id IN ( SELECT id FROM screens WHERE "order" > NEW.max_screens AND group_id = new.id);
		DELETE FROM screens WHERE  "order" > NEW.max_screens AND group_id = new.id;
	ELSE
		forstart = OLD.max_screens+1;
		FOR i IN forstart..NEW.max_screens LOOP
		    INSERT INTO screens (group_id, "order") values (NEW.id, i);
		END LOOP;
	END IF;
	RETURN NULL;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION group_update()
  OWNER TO postgres;

------------------------------------------
------------ CREATE TRIGGERS -------------
------------------------------------------
-- Trigger: group_modified on groups
CREATE TRIGGER group_modified
  AFTER UPDATE
  ON groups
  FOR EACH ROW
  EXECUTE PROCEDURE group_update(); 
