--
-- content_symlink__new/8
--
create or replace function content_symlink__new(
  character varying,
  character varying,
  integer,
  integer,
  integer,
  timestamp with time zone,
  integer,
  character varying
) returns int4 as $$

declare
  new__name                   alias for $1;  -- default null  
  new__label                  alias for $2;  -- default null
  new__target_id              alias for $3;  
  new__parent_id              alias for $4;  
  new__symlink_id             alias for $5;  -- default null
  new__creation_date          alias for $6;  -- default now()
  new__creation_user          alias for $7;  -- default null
  new__creation_ip            alias for $8;  -- default null
  v_symlink_id                cr_symlinks.symlink_id%TYPE;
  v_name                      cr_items.name%TYPE;
  v_label                     cr_symlinks.label%TYPE;
  v_ctype                     varchar;
begin

  -- SOME CHECKS --

  -- 1) check that the target is now a symlink
  if content_symlink__is_symlink(new__target_id) = 't' then
    raise EXCEPTION '-20000: Cannot create a symlink to a symlink %', new__target_id;
  end if;

  -- 2) check that the parent is a folder
  if content_folder__is_folder(new__parent_id) = 'f' then
    raise EXCEPTION '-20000: The parent is not a folder';
  end if;

  -- 3) check that parent folder supports symlinks
  if content_folder__is_registered(new__parent_id,'content_symlink','f') = 'f' then
    raise EXCEPTION '-20000: This folder does not allow symlinks to be created';
  end if;

  -- 4) check that the content folder supports the target items content type
  if content_folder__is_registered(new__parent_id, content_item__get_content_type(new__target_id), 'f') = 'f' then

    v_ctype := content_item__get_content_type(new__target_id);
    raise EXCEPTION '-20000: This folder does not allow symlinks to items of type % to be created', v_ctype;
  end if;

  -- PASSED ALL CHECKS --

  -- Select default name if the name is null
  if  new__name is null or new__name = '' then
    select 
      'symlink_to_' ||  name into v_name
    from 
      cr_items
    where
       item_id =  new__target_id;
  
    if NOT FOUND then 
       v_name := null;
    end if;
  else
    v_name :=  new__name;
  end if;

  -- Select default label if the label is null
  if new__label is null then
    v_label := 'Symlink to ' || v_name;
  else
    v_label := new__label;
  end if;

  v_symlink_id := content_item__new(
      v_name, 
      new__parent_id,
      new__symlink_id,
      null,
      new__creation_date, 
      new__creation_user, 
      null,
      new__creation_ip, 
      'content_item',
      'content_symlink', 
      null,
      null,
      'text/plain',
      null,
      null,
      'text'
  );

  insert into cr_symlinks
    (symlink_id, target_id, label)
  values
    (v_symlink_id, new__target_id, v_label);

  return v_symlink_id;

end;$$ language plpgsql;