--
-- time_interval__edit/3
--
create or replace function time_interval__edit(
  integer,
  timestamp with time zone,
  timestamp with time zone
) returns int4 as $$

declare
        edit__interval_id     alias for $1;
        edit__start_date      alias for $2; -- default null,
        edit__end_date        alias for $3; -- default null
begin

	-- JS: I hate deeply nested if-else-ifs!!! 

        -- Null for start_date or end_date means dont change.
        if edit__start_date is not null and edit__end_date is not null then
            update time_intervals
            set    start_date  = edit__start_date,
                   end_date    = edit__end_date
            where  interval_id = edit__interval_id;
	end if;

	-- Update only the end date if not null even if start date is null
        if edit__start_date is not null and edit__end_date is null 
        then
            update time_intervals
            set    start_date  = edit__start_date
            where  interval_id = edit__interval_id;
	end if;
	    
	-- Update only the start date if not null even if end date is null
        if edit__end_date is not null and edit__start_date is null 
	then
                 update time_intervals
		 set end_date       = edit__end_date
		 where interval_id  = edit__interval_id;
	end if;

	return 0;

end;$$ language plpgsql;