--
-- membership_rels_in_tr/0
--
create or replace function membership_rels_in_tr(
  
) returns trigger as $$

DECLARE
  v_object_id_one acs_rels.object_id_one%TYPE;
  v_object_id_two acs_rels.object_id_two%TYPE;
  v_rel_type      acs_rels.rel_type%TYPE;
  v_composable_p  acs_rel_types.composable_p%TYPE;
  v_error         text;
  map             record;
BEGIN
  
  -- First check if added this relation violated any relational constraints
  v_error := rel_constraint__violation(new.rel_id);
  if v_error is not null then
      raise EXCEPTION '-20000: %', v_error;
  end if;

  select object_id_one, object_id_two, r.rel_type, composable_p
  into v_object_id_one, v_object_id_two, v_rel_type, v_composable_p
  from acs_rels r
  join acs_rel_types t on (r.rel_type = t.rel_type)
  where rel_id = new.rel_id;

  -- Insert a row for me in the group_element_index.
  insert into group_element_index
   (group_id, element_id, rel_id, container_id, 
    rel_type, ancestor_rel_type)
  values
   (v_object_id_one, v_object_id_two, new.rel_id, v_object_id_one, 
    v_rel_type, 'membership_rel');

  if new.member_state = 'approved' then
    perform party_approved_member__add(v_object_id_one, v_object_id_two, new.rel_id, v_rel_type);
  end if;

  -- If this rel_type composable...
  if v_composable_p = 't' then

     -- For all groups of which I am a component, insert a
     -- row in the group_element_index.
     for map in select distinct group_id
          from group_component_map
          where component_id = v_object_id_one 
     loop

        insert into group_element_index
               (group_id, element_id, rel_id, container_id,
               rel_type, ancestor_rel_type)
        values
               (map.group_id, v_object_id_two, new.rel_id, v_object_id_one,
               v_rel_type, 'membership_rel');

        if new.member_state = 'approved' then
           perform party_approved_member__add(map.group_id, v_object_id_two, new.rel_id, v_rel_type);
        end if;

     end loop;
  end if;
  return new;

END;
$$ language plpgsql;