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

declare
  copy__symlink_id             alias for $1;  
  copy__target_folder_id       alias for $2;  
  copy__creation_user          alias for $3;  
  copy__creation_ip            alias for $4;  -- default null  
  v_current_folder_id          cr_folders.folder_id%TYPE;
  v_name                       cr_items.name%TYPE;
  v_target_id                  cr_items.item_id%TYPE;
  v_label                      cr_symlinks.label%TYPE;
  v_symlink_id                 cr_symlinks.symlink_id%TYPE;
begin

  if content_folder__is_folder(copy__target_folder_id) = 't' then
    select
      parent_id
    into
      v_current_folder_id
    from
      cr_items
    where
      item_id = copy__symlink_id;

    -- can't copy to the same folder
    if copy__target_folder_id != v_current_folder_id then

      select
        i.name, content_symlink__resolve(i.item_id), s.label
      into
        v_name, v_target_id, v_label
      from
        cr_symlinks s, cr_items i
      where
        s.symlink_id = i.item_id
      and
        s.symlink_id = copy__symlink_id;


      if content_folder__is_registered(copy__target_folder_id,
        'content_symlink','f') = 't' then
        if content_folder__is_registered(copy__target_folder_id,
          content_item__get_content_type(content_symlink__resolve(copy__symlink_id)),'f') = 't' then

          v_symlink_id := content_symlink__new(
              v_name,
	      v_label,
              v_target_id,
              copy__target_folder_id,
              null,
              now(),
	      copy__creation_user,
	      copy__creation_ip
          );


	end if;
      end if;
    end if;
  end if;

  return 0; 
end;$$ language plpgsql;