private void updateDialog(QBDialog dialog, QBCustomObjectUpdateBuilder requestBuilder)
     throws QBResponseException {
   QBDialog updatedDialog = groupChatManager.updateDialog(dialog, requestBuilder);
   ArrayList<Integer> friendsList = new ArrayList<Integer>(updatedDialog.getOccupants());
   friendsList.remove(chatCreator.getId());
   notifyFriendsRoomUpdate(updatedDialog, friendsList);
   DatabaseManager.saveDialog(context, updatedDialog);
 }
  public void removeUsersFromRoom(String roomJid, List<Integer> userIdsList)
      throws QBResponseException {
    QBDialog dialog = DatabaseManager.getDialogByRoomJid(context, roomJid);

    QBCustomObjectUpdateBuilder requestBuilder = new QBCustomObjectUpdateBuilder();
    requestBuilder.pullAll(com.quickblox.chat.Consts.DIALOG_OCCUPANTS, userIdsList.toArray());
    updateDialog(dialog, requestBuilder);
  }
  public void addUsersToRoom(String dialogId, List<Integer> userIdsList) throws Exception {
    QBDialog dialog = DatabaseManager.getDialogByDialogId(context, dialogId);

    QBCustomObjectUpdateBuilder requestBuilder = new QBCustomObjectUpdateBuilder();
    requestBuilder.push(com.quickblox.chat.Consts.DIALOG_OCCUPANTS, userIdsList.toArray());
    updateDialog(dialog, requestBuilder);

    inviteFriendsToRoom(dialog, userIdsList);
  }
  public void leaveRoomChat(String roomJid)
      throws XMPPException, SmackException.NotConnectedException, QBResponseException {
    groupChatManager.getGroupChat(roomJid).leave();
    List<Integer> userIdsList = new ArrayList<Integer>();
    userIdsList.add(chatCreator.getId());
    removeUsersFromRoom(roomJid, userIdsList);

    DatabaseManager.deleteDialogByRoomJid(context, roomJid);
  }
 @Override
 public void execute(Bundle bundle) {
   QBDialog dialog = (QBDialog) bundle.getSerializable(QBServiceConsts.EXTRA_DIALOG);
   groupDialog =
       new GroupDialog(
           DatabaseManager.getDialogByDialogId(
               GroupDialogDetailsActivity.this, dialog.getDialogId()));
   updateOldGroupData();
   hideProgress();
 }
  public Collection<User> loadUsers(Collection<Integer> usersIdsList) throws QBResponseException {
    Collection<QBUser> usersList = (Collection<QBUser>) QBUsers.getUsersByIDs(usersIdsList, null);

    Collection<User> usersListResult = FriendUtils.createUsersList(usersList);

    if (usersList != null) {
      DatabaseManager.saveUsers(context, usersListResult);
    }

    return usersListResult;
  }
  public User loadUser(int userId) throws QBResponseException {
    QBUser user = QBUsers.getUser(userId);
    User resultUser = null;

    if (user != null) {
      resultUser = FriendUtils.createUser(user);
      DatabaseManager.saveUser(context, resultUser);
    }

    return resultUser;
  }
 public void tryJoinRoomChats(List<QBDialog> chatDialogsList) {
   if (!chatDialogsList.isEmpty()) {
     DatabaseManager.saveDialogs(context, chatDialogsList);
     initGroupDialogsList();
     for (QBDialog dialog : chatDialogsList) {
       if (!QBDialogType.PRIVATE.equals(dialog.getType())) {
         groupDialogsList.add(dialog);
         tryJoinRoomChat(dialog);
       }
     }
   }
 }
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_group_dialog_details);
   dialogId = (String) getIntent().getExtras().getSerializable(QBServiceConsts.EXTRA_DIALOG_ID);
   dialogCurrent = DatabaseManager.getDialogByDialogId(this, dialogId);
   groupDialog = new GroupDialog(dialogCurrent);
   imageUtils = new ImageUtils(this);
   initUI();
   initUIWithData();
   addActions();
   startLoadGroupDialog();
 }
  private int getItemViewType(Cursor cursor) {
    MessageCache messageCache = DatabaseManager.getMessageCacheFromCursor(cursor);
    boolean ownMessage = isOwnMessage(messageCache.getSenderId());
    boolean friendsRequestMessage = messageCache.getFriendsNotificationType() != null;

    if (!friendsRequestMessage) {
      if (ownMessage) {
        return TYPE_OWN_MESSAGE;
      } else {
        return TYPE_OPPONENT_MESSAGE;
      }
    } else {
      return TYPE_REQUEST_MESSAGE;
    }
  }
    @Override
    public void processMessage(QBGroupChat groupChat, QBChatMessage chatMessage) {
      User user = DatabaseManager.getUserById(context, chatMessage.getSenderId());
      String attachUrl = ChatUtils.getAttachUrlIfExists(chatMessage);
      String dialogId = chatMessage.getProperty(ChatUtils.PROPERTY_DIALOG_ID);
      long time = Long.parseLong(chatMessage.getProperty(ChatUtils.PROPERTY_DATE_SENT).toString());
      String messageId = chatMessage.getProperty(ChatUtils.PROPERTY_MESSAGE_ID).toString();
      String messageType = chatMessage.getProperty(ChatUtils.PROPERTY_NOTIFICATION_TYPE);
      if (ChatUtils.PROPERTY_NOTIFICATION_TYPE_CREATE_CHAT.equals(messageType)) {
        if (chatMessage.getBody().equals("join") || chatMessage.getBody().equals("stay")) {
          if (dialogId.equals(ChatUtils.joinDialogId) && user != null) {
            ChatUtils.setJoinUsers(user);
            if (chatMessage.getBody().equals("join")) {
              sendOccupantStatusGroup("stay");
            }
          }
          return;
        } else if (chatMessage.getBody().equals("leave")) {
          if (dialogId.equals(ChatUtils.joinDialogId) && user != null)
            ChatUtils.removeJoinUsers(user);
          return;
        }
      }

      if (user == null) {
        user = new User();
        user.setUserId(chatMessage.getSenderId());
        user.setFullName(chatMessage.getSenderId() + ConstsCore.EMPTY_STRING);
      }

      saveMessageToCache(
          new MessageCache(
              messageId,
              dialogId,
              chatMessage.getSenderId(),
              chatMessage.getBody(),
              attachUrl,
              time,
              false,
              false,
              false));

      if (!chatMessage.getSenderId().equals(chatCreator.getId())) {
        // TODO IS handle logic when friend is not in the friend list
        notifyMessageReceived(chatMessage, user, dialogId, false);
      }
    }
  @Override
  public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view;
    ViewHolder viewHolder = new ViewHolder();

    MessageCache messageCache = DatabaseManager.getMessageCacheFromCursor(cursor);
    boolean ownMessage = isOwnMessage(messageCache.getSenderId());

    if (messageCache.getFriendsNotificationType() == null) {
      if (ownMessage) {
        view = layoutInflater.inflate(R.layout.list_item_message_own, null, true);
      } else {
        view = layoutInflater.inflate(R.layout.list_item_private_message_opponent, null, true);
      }

      viewHolder.attachMessageRelativeLayout =
          (RelativeLayout) view.findViewById(R.id.attach_message_relativelayout);
      viewHolder.timeAttachMessageTextView =
          (TextView) view.findViewById(R.id.time_attach_message_textview);
      viewHolder.progressRelativeLayout =
          (RelativeLayout) view.findViewById(R.id.progress_relativelayout);
      viewHolder.textMessageView = view.findViewById(R.id.text_message_view);
      viewHolder.messageTextView = (EmojiTextView) view.findViewById(R.id.message_textview);
      viewHolder.attachImageView = (MaskedImageView) view.findViewById(R.id.attach_imageview);
      viewHolder.timeTextMessageTextView =
          (TextView) view.findViewById(R.id.time_text_message_textview);
      viewHolder.verticalProgressBar = (ProgressBar) view.findViewById(R.id.vertical_progressbar);
      viewHolder.verticalProgressBar.setProgressDrawable(
          context.getResources().getDrawable(R.drawable.vertical_progressbar));
      viewHolder.centeredProgressBar = (ProgressBar) view.findViewById(R.id.centered_progressbar);
    } else {
      view = layoutInflater.inflate(R.layout.list_item_friends_request_message, null, true);

      viewHolder.messageTextView = (EmojiTextView) view.findViewById(R.id.message_textview);
      viewHolder.timeTextMessageTextView =
          (TextView) view.findViewById(R.id.time_text_message_textview);
      viewHolder.acceptFriendImageView =
          (ImageView) view.findViewById(R.id.accept_friend_imagebutton);
      viewHolder.dividerView = view.findViewById(R.id.divider_view);
      viewHolder.rejectFriendImageView =
          (ImageView) view.findViewById(R.id.reject_friend_imagebutton);
    }

    view.setTag(viewHolder);

    return view;
  }
  @Override
  public void bindView(View view, Context context, final Cursor cursor) {
    final ViewHolder viewHolder = (ViewHolder) view.getTag();

    final User friend = DatabaseManager.getUserFromCursor(cursor);

    viewHolder.nameTextView.setText(friend.getFullName());
    //        viewHolder.statusMessageTextView.setText(friend.getStatus());
    viewHolder.nameTextView.setText(friend.getFullName());

    if (friend.isOnline()) {
      viewHolder.onlineImageView.setVisibility(View.VISIBLE);
    } else {
      viewHolder.onlineImageView.setVisibility(View.GONE);
    }

    final int position = cursor.getPosition();

    viewHolder.selectFriendCheckBox.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View view) {
            CheckBox checkBox = (CheckBox) view;
            sparseArrayCheckBoxes.put(position, checkBox.isChecked());
            friend.setSelected(checkBox.isChecked());
            notifyCounterChanged(checkBox.isChecked());
            if (checkBox.isChecked()) {
              selectedFriends.add(friend);
            } else if (selectedFriends.contains(friend)) {
              selectedFriends.remove(friend);
            }
            viewHolder.contentRelativeLayout.setBackgroundColor(
                getBackgroundColorItem(viewHolder.selectFriendCheckBox.isChecked()));
          }
        });

    boolean checked = sparseArrayCheckBoxes.get(position);

    viewHolder.selectFriendCheckBox.setChecked(checked);

    String avatarUrl = getAvatarUrlForFriend(friend);
    displayAvatarImage(avatarUrl, viewHolder.avatarImageView);

    viewHolder.contentRelativeLayout.setBackgroundColor(getBackgroundColorItem(checked));
  }
  private void findLastFriendsRequestForCursor(Cursor cursor) {
    boolean ownMessage;
    boolean friendsRequestMessage;
    boolean isFriend;

    MessageCache messageCache = DatabaseManager.getMessageCacheFromCursor(cursor);
    if (messageCache.getFriendsNotificationType() != null) {
      ownMessage = isOwnMessage(messageCache.getSenderId());
      friendsRequestMessage =
          FriendsNotificationType.REQUEST.equals(messageCache.getFriendsNotificationType());

      if (friendsRequestMessage && !ownMessage) {
        //                isFriend = DatabaseManager.isFriendInBase(context,
        // messageCache.getSenderId());
        isFriend = true;
        if (!isFriend) {
          lastRequestPosition = cursor.getPosition();
        }
      }
    }
  }
  @Override
  public void bindView(View view, final Context context, Cursor cursor) {
    ViewHolder viewHolder = (ViewHolder) view.getTag();

    MessageCache messageCache = DatabaseManager.getMessageCacheFromCursor(cursor);

    boolean ownMessage = isOwnMessage(messageCache.getSenderId());
    boolean friendsRequestMessage =
        FriendsNotificationType.REQUEST.equals(messageCache.getFriendsNotificationType());
    boolean friendsInfoRequestMessage =
        messageCache.getFriendsNotificationType() != null && !friendsRequestMessage;

    if (friendsRequestMessage) {
      viewHolder.messageTextView.setText(messageCache.getMessage());
      viewHolder.timeTextMessageTextView.setText(
          DateUtils.longToMessageDate(messageCache.getTime()));

      setVisibilityFriendsActions(viewHolder, View.GONE);
    } else if (friendsInfoRequestMessage) {
      viewHolder.messageTextView.setText(messageCache.getMessage());
      viewHolder.timeTextMessageTextView.setText(
          DateUtils.longToMessageDate(messageCache.getTime()));

      setVisibilityFriendsActions(viewHolder, View.GONE);

      lastInfoRequestPosition = cursor.getPosition();
    } else if (!TextUtils.isEmpty(messageCache.getAttachUrl())) {
      resetUI(viewHolder);

      setViewVisibility(viewHolder.progressRelativeLayout, View.VISIBLE);
      viewHolder.timeAttachMessageTextView.setText(
          DateUtils.longToMessageDate(messageCache.getTime()));
      displayAttachImage(messageCache.getAttachUrl(), viewHolder);
    } else {
      resetUI(viewHolder);

      setViewVisibility(viewHolder.textMessageView, View.VISIBLE);
      viewHolder.messageTextView.setText(messageCache.getMessage());
      viewHolder.timeTextMessageTextView.setText(
          DateUtils.longToMessageDate(messageCache.getTime()));
    }

    if (ownMessage && !friendsRequestMessage && !friendsInfoRequestMessage) {
      setMessageStatus(
          view,
          viewHolder,
          R.id.text_message_delivery_status_imageview,
          messageCache.isDelivered(),
          messageCache.isRead());
    }

    if (!messageCache.isRead() && !ownMessage) {
      messageCache.setRead(true);
      QBUpdateStatusMessageCommand.start(context, dialog, messageCache, true);
    }

    // check if last message is request message
    boolean lastRequestMessage =
        cursor.getPosition() == cursor.getCount() - 1 && friendsRequestMessage;
    if (lastRequestMessage) {
      findLastFriendsRequestForCursor(cursor);
    }

    // check if friend was rejected/deleted.
    if (lastRequestPosition != EMPTY_POSITION && lastRequestPosition < lastInfoRequestPosition) {
      lastRequestPosition = EMPTY_POSITION;
    } else if ((lastRequestPosition != EMPTY_POSITION
        && lastRequestPosition == cursor.getPosition())) { // set visible friends actions
      setVisibilityFriendsActions(viewHolder, View.VISIBLE);
      initListeners(viewHolder, messageCache.getSenderId());
    }
  }