--
-- content_type__register_template/4
--
create or replace function content_type__register_template(
  character varying,
  integer,
  character varying,
  boolean
) returns int4 as $$

declare
  register_template__content_type           alias for $1;  
  register_template__template_id            alias for $2;  
  register_template__use_context            alias for $3;  
  register_template__is_default             alias for $4;  -- default 'f'  
  v_template_registered                     boolean;       
begin
  select 
    count(*) > 0 into v_template_registered
  from
    cr_type_template_map
  where
    content_type = register_template__content_type
  and
    use_context =  register_template__use_context
  and
    template_id =  register_template__template_id;

  -- register the template
  if NOT v_template_registered then
    insert into cr_type_template_map (
      template_id, content_type, use_context, is_default
    ) values (
      register_template__template_id, register_template__content_type, 
      register_template__use_context, register_template__is_default
    );

  -- update the registration status of the template
  else

    -- unset the default template before setting this one as the default
    if register_template__is_default then
      update cr_type_template_map
        set is_default = 'f'
        where content_type = register_template__content_type
        and use_context = register_template__use_context;
    end if;

    update cr_type_template_map
      set is_default =    register_template__is_default
      where template_id = register_template__template_id
      and content_type =  register_template__content_type
      and use_context =   register_template__use_context;
  end if;

  return 0; 
end;$$ language plpgsql;