/**
   * Removes the relation (and its inverse in case of a bidirectional relation) from the database.
   *
   * @param relation the relation to be removed
   * @throws PortalException if the relation is bidirectional and its inverse relation could not be
   *     found
   * @throws SystemException if a system exception occurred
   */
  public void deleteRelation(SocialRelation relation) throws PortalException, SystemException {

    socialRelationPersistence.remove(relation);

    if (SocialRelationConstants.isTypeBi(relation.getType())) {
      SocialRelation biRelation =
          socialRelationPersistence.findByU1_U2_T(
              relation.getUserId2(), relation.getUserId1(), relation.getType());

      socialRelationPersistence.remove(biRelation);
    }
  }
  /**
   * Adds a social relation between the two users to the database.
   *
   * @param userId1 the user that is the subject of the relation
   * @param userId2 the user at the other end of the relation
   * @param type the type of the relation
   * @return the social relation
   * @throws PortalException if the users could not be found, if the users were not from the same
   *     company, or if either of the users was the default user
   * @throws SystemException if a system exception occurred
   */
  public SocialRelation addRelation(long userId1, long userId2, int type)
      throws PortalException, SystemException {

    if (userId1 == userId2) {
      throw new RelationUserIdException();
    }

    User user1 = userPersistence.findByPrimaryKey(userId1);
    User user2 = userPersistence.findByPrimaryKey(userId2);

    if (user1.getCompanyId() != user2.getCompanyId()) {
      throw new RelationUserIdException();
    }

    SocialRelation relation = socialRelationPersistence.fetchByU1_U2_T(userId1, userId2, type);

    if (relation == null) {
      long relationId = counterLocalService.increment();

      relation = socialRelationPersistence.create(relationId);

      relation.setCompanyId(user1.getCompanyId());
      relation.setCreateDate(System.currentTimeMillis());
      relation.setUserId1(userId1);
      relation.setUserId2(userId2);
      relation.setType(type);

      socialRelationPersistence.update(relation);
    }

    if (SocialRelationConstants.isTypeBi(type)) {
      SocialRelation biRelation = socialRelationPersistence.fetchByU1_U2_T(userId2, userId1, type);

      if (biRelation == null) {
        long biRelationId = counterLocalService.increment();

        biRelation = socialRelationPersistence.create(biRelationId);

        biRelation.setCompanyId(user1.getCompanyId());
        biRelation.setCreateDate(System.currentTimeMillis());
        biRelation.setUserId1(userId2);
        biRelation.setUserId2(userId1);
        biRelation.setType(type);

        socialRelationPersistence.update(biRelation);
      }
    }

    return relation;
  }