--------------------------------------------------------
--  DDL for Procedure P_MANAGE_USERS_OLD
--------------------------------------------------------
set define off;

  CREATE OR REPLACE EDITIONABLE PROCEDURE "ENVX_OPER"."P_MANAGE_USERS_OLD" (pi_id_role IN NUMBER,
											  pi_id_sys_profile IN NUMBER,
											  pi_status IN VARCHAR2,
											  pi_user_name IN VARCHAR2,
											  pi_ldap_user IN VARCHAR2,
											  pi_user_mail IN VARCHAR2,
											  pi_app_id NUMBER,
											  pi_apex_role NUMBER) AS
  
  
  BEGIN

	--Elimino los roles donde pertenezca el usuario--
    FOR c IN (
        SELECT DISTINCT
            user_name,
            id_apex_role
        FROM
            user_roles       u,
            system_profile   p,
            system_role      r
        WHERE
            u.id_sys_profile = p.id_sys_profile
            AND p.id_role = r.id_role
            AND upper(user_name) = upper(pi_user_name)
    ) LOOP 

		apex_acl.remove_user_role(p_application_id => pi_app_id, 
								  p_user_name => upper(pi_user_name), 
								  p_role_id => c.id_apex_role
								  );

    END LOOP;


	--Actualizar el perfil y rol correspondiente--
	UPDATE user_roles
	set id_sys_profile = pi_id_sys_profile,
		id_role = pi_id_role,
		user_mail = pi_user_mail
	where user_name = pi_user_name;

	--Buscar si actualizo algun registro--
	IF sql%rowcount = 0 THEN

	  --Si no actualizo ninguno, inserto el registro--	
	  INSERT INTO user_roles (
		id_user,
		id_role,
		id_sys_profile,
		user_name,
		user_mail
	) VALUES (
		S_USER_ROLES_ID.nextval,
		pi_id_role,
		pi_id_sys_profile,
		pi_user_name,
		pi_user_mail
	);

	END IF;

	IF pi_status = 1 THEN
	--Agrego el rol de apex correspondiente--
	apex_acl.add_user_role(p_application_id => pi_app_id, 
					   p_user_name => upper(pi_user_name), 
					   p_role_id => pi_apex_role
					   );
	END IF;


  END;

/
