--
-- acs_user__new/5
--
create or replace function acs_user__new(
  character varying,
  character varying,
  character varying,
  character,
  character
) returns int4 as $$

declare
        email   alias for $1;
        fname   alias for $2;
        lname   alias for $3;
        pword   alias for $4;
        salt    alias for $5;
begin
        return acs_user__new(null,
                             'user',
                             now(),
                             null,
                             null,                
                             email,
                             null,
                             fname,
                             lname,
                             pword,
                             salt,
                             null,
                             null,
                             null,
                             't',
                             null
                             );

end;$$ language plpgsql;


--
-- acs_user__new/16
--
create or replace function acs_user__new(
  p_user_id integer,
  p_object_type character varying,
  p_creation_date timestamp with time zone,
  p_creation_user integer,
  p_creation_ip character varying,
  p_authority_id integer,
  p_username character varying,
  p_email character varying,
  p_url character varying,
  p_first_names character varying,
  p_last_name character varying,
  p_password character,
  p_salt character,
  p_screen_name character varying,
  p_email_verified_p boolean,
  p_context_id integer
) returns int4 as $$

DECLARE
    v_user_id                  users.user_id%TYPE;
    v_authority_id             auth_authorities.authority_id%TYPE;
    v_person_exists            integer;			
BEGIN
    v_user_id := p_user_id;

    select 1 from persons into v_person_exists where person_id = v_user_id;

    if NOT FOUND then
        v_user_id := person__new(
            v_user_id, 
            p_object_type,
            p_creation_date, 
            p_creation_user, 
            p_creation_ip,
            p_email, 
            p_url, 
            p_first_names, 
            p_last_name, 
            p_context_id
        );
    else
     update acs_objects set object_type = 'user' where object_id = v_user_id;
    end if;

    -- default to local authority
    if p_authority_id is null then
        select authority_id
        into   v_authority_id
        from   auth_authorities
        where  short_name = 'local';
    else
        v_authority_id := p_authority_id;
    end if;

    insert into users
       (user_id, authority_id, username, password, salt, screen_name, email_verified_p)
    values
       (v_user_id, v_authority_id, p_username, p_password, p_salt, p_screen_name, p_email_verified_p);

    insert into user_preferences
      (user_id)
      values
      (v_user_id);

    return v_user_id;
  
END;
$$ language plpgsql;