Example usage for android.util SparseIntArray keyAt

List of usage examples for android.util SparseIntArray keyAt

Introduction

In this page you can find the example usage for android.util SparseIntArray keyAt.

Prototype

public int keyAt(int index) 

Source Link

Document

Given an index in the range 0...size()-1, returns the key from the indexth key-value mapping that this SparseIntArray stores.

Usage

From source file:net.sf.sprockets.util.SparseArrays.java

/**
 * Get the keys of the SparseIntArray.//from  ww  w .  ja v  a  2s.  c  o  m
 */
public static int[] keys(SparseIntArray array) {
    int[] keys = new int[array.size()];
    for (int i = 0; i < keys.length; i++) {
        keys[i] = array.keyAt(i);
    }
    return keys;
}

From source file:Main.java

/**
 * internal method to handle the selections if items are added / removed
 *
 * @param positions     the positions map which should be adjusted
 * @param startPosition the global index of the first element modified
 * @param endPosition   the global index up to which the modification changed the indices (should be MAX_INT if we check til the end)
 * @param adjustBy      the value by which the data was shifted
 * @return the adjusted map/*from   w  w  w . j  a  va2s  .  com*/
 */
public static SparseIntArray adjustPosition(SparseIntArray positions, int startPosition, int endPosition,
        int adjustBy) {
    SparseIntArray newPositions = new SparseIntArray();

    for (int i = 0, size = positions.size(); i < size; i++) {
        int position = positions.keyAt(i);

        //if our current position is not within the bounds to check for we can add it
        if (position < startPosition || position > endPosition) {
            newPositions.put(position, positions.valueAt(i));
        } else if (adjustBy > 0) {
            //if we added items and we are within the bounds we can simply add the adjustBy to our entry
            newPositions.put(position + adjustBy, positions.valueAt(i));
        } else if (adjustBy < 0) {
            //if we removed items and we are within the bounds we have to check if the item was removed
            //adjustBy is negative in this case
            if (position > startPosition + adjustBy && position <= startPosition) {
                ;//we are within the removed items range we don't add this item anymore
            } else {
                //otherwise we adjust our position
                newPositions.put(position + adjustBy, positions.valueAt(i));
            }
        }
    }

    return newPositions;
}

From source file:io.fabric.samples.cannonball.activity.PoemBuilderActivity.java

private void createPoem() {
    if (poemContainer.getChildCount() > 0) {
        final String poemText = getPoemText();
        final SparseIntArray imgList = poemTheme.getImageList();
        // the line below seems weird, but relies on the fact that the index of SparseIntArray could be any integer
        final int poemImage = imgList
                .keyAt(imgList.indexOfValue(imgList.get(poemImagePager.getCurrentItem() + 1)));
        Crashlytics.setString(App.CRASHLYTICS_KEY_POEM_TEXT, poemText);
        Crashlytics.setInt(App.CRASHLYTICS_KEY_POEM_IMAGE, poemImage);

        AppService.createPoem(getApplicationContext(), poemText, poemImage, poemTheme.getDisplayName(),
                dateFormat.format(Calendar.getInstance().getTime()));
    } else {/*from  w w  w.j a  v a2 s . c  o m*/
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_wordless_poem),
                Toast.LENGTH_SHORT).show();
        Crashlytics.log("PoemBuilder: User tried to create poem without words on it");
    }
}

From source file:galilei.kelimekavanozu.activity.PoemBuilderActivity.java

private void createPoem() {
    if (poemContainer.getChildCount() > 0) {
        final String poemText = getPoemText();
        final SparseIntArray imgList = poemTheme.getImageList();
        // the line below seems weird, but relies on the fact that the index of SparseIntArray could be any integer
        final int poemImage = imgList
                .keyAt(imgList.indexOfValue(imgList.get(poemImagePager.getCurrentItem() + 1)));
        Crashlytics.setString(App.CRASHLYTICS_KEY_POEM_TEXT, poemText);
        Crashlytics.setInt(App.CRASHLYTICS_KEY_POEM_IMAGE, poemImage);

        Answers.getInstance().logCustom(
                new CustomEvent("clicked save poem").putCustomAttribute("poem size", poemText.length())
                        .putCustomAttribute("poem theme", poemTheme.getDisplayName())
                        .putCustomAttribute("poem image", poemImage));

        AppService.createPoem(getApplicationContext(), poemText, poemImage, poemTheme.getDisplayName(),
                dateFormat.format(Calendar.getInstance().getTime()));
    } else {/*from  ww  w.  j  av a 2s.  c o  m*/
        Toast.makeText(getApplicationContext(), getResources().getString(R.string.toast_wordless_poem),
                Toast.LENGTH_SHORT).show();
        Crashlytics.log("PoemBuilder: User tried to create poem without words on it");
    }
}

From source file:org.chromium.chrome.browser.tabmodel.TabPersistentStore.java

private void restoreTab(TabRestoreDetails tabToRestore, TabState tabState, boolean setAsActive) {
    // If we don't have enough information about the Tab, bail out.
    boolean isIncognito = isIncognitoTabBeingRestored(tabToRestore, tabState);
    if (tabState == null) {
        if (tabToRestore.isIncognito == null) {
            Log.w(TAG, "Failed to restore tab: not enough info about its type was available.");
            return;
        } else if (isIncognito) {
            Log.i(TAG, "Failed to restore Incognito tab: its TabState could not be restored.");
            return;
        }// w  ww.  j  a  v a  2 s. co  m
    }

    TabModel model = mTabModelSelector.getModel(isIncognito);
    SparseIntArray restoredTabs = isIncognito ? mIncognitoTabsRestored : mNormalTabsRestored;
    int restoredIndex = 0;
    if (tabToRestore.fromMerge) {
        // Put any tabs being merged into this list at the end.
        restoredIndex = mTabModelSelector.getModel(isIncognito).getCount();
    } else if (restoredTabs.size() > 0
            && tabToRestore.originalIndex > restoredTabs.keyAt(restoredTabs.size() - 1)) {
        // If the tab's index is too large, restore it at the end of the list.
        restoredIndex = restoredTabs.size();
    } else {
        // Otherwise try to find the tab we should restore before, if any.
        for (int i = 0; i < restoredTabs.size(); i++) {
            if (restoredTabs.keyAt(i) > tabToRestore.originalIndex) {
                Tab nextTabByIndex = TabModelUtils.getTabById(model, restoredTabs.valueAt(i));
                restoredIndex = nextTabByIndex != null ? model.indexOf(nextTabByIndex) : -1;
                break;
            }
        }
    }

    int tabId = tabToRestore.id;
    if (tabState != null) {
        mTabCreatorManager.getTabCreator(isIncognito).createFrozenTab(tabState, tabToRestore.id, restoredIndex);
    } else {
        Log.w(TAG, "Failed to restore TabState; creating Tab with last known URL.");
        Tab fallbackTab = mTabCreatorManager.getTabCreator(isIncognito)
                .createNewTab(new LoadUrlParams(tabToRestore.url), TabModel.TabLaunchType.FROM_RESTORE, null);
        tabId = fallbackTab.getId();
        model.moveTab(tabId, restoredIndex);
    }

    // If the tab is being restored from a merge and its index is 0, then the model being
    // merged into doesn't contain any tabs. Select the first tab to avoid having no tab
    // selected. TODO(twellington): The first tab will always be selected. Instead, the tab that
    // was selected in the other model before the merge should be selected after the merge.
    if (setAsActive || (tabToRestore.fromMerge && restoredIndex == 0)) {
        boolean wasIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();
        int selectedModelTabCount = mTabModelSelector.getCurrentModel().getCount();

        TabModelUtils.setIndex(model, TabModelUtils.getTabIndexById(model, tabId));
        boolean isIncognitoTabModelSelected = mTabModelSelector.isIncognitoSelected();

        // Setting the index will cause the tab's model to be selected. Set it back to the model
        // that was selected before setting the index if the index is being set during a merge
        // unless the previously selected model is empty (e.g. showing the empty background
        // view on tablets).
        if (tabToRestore.fromMerge && wasIncognitoTabModelSelected != isIncognitoTabModelSelected
                && selectedModelTabCount != 0) {
            mTabModelSelector.selectModel(wasIncognitoTabModelSelected);
        }
    }
    restoredTabs.put(tabToRestore.originalIndex, tabId);
}

From source file:net.bluehack.ui.ChatActivity.java

@Override
public void didReceivedNotification(int id, final Object... args) {
    if (id == NotificationCenter.messagesDidLoaded) {
        int guid = (Integer) args[10];
        if (guid == classGuid) {
            if (!openAnimationEnded) {
                NotificationCenter.getInstance().setAllowedNotificationsDutingAnimation(new int[] {
                        NotificationCenter.chatInfoDidLoaded, NotificationCenter.dialogsNeedReload,
                        NotificationCenter.closeChats,
                        NotificationCenter.botKeyboardDidLoaded/*, NotificationCenter.botInfoDidLoaded*/ });
            }/*  www  . j  a  va 2 s  .com*/
            int queryLoadIndex = (Integer) args[11];
            int index = waitingForLoad.indexOf(queryLoadIndex);
            if (index == -1) {
                return;
            } else {
                waitingForLoad.remove(index);
            }
            ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[2];
            if (waitingForReplyMessageLoad) {
                boolean found = false;
                for (int a = 0; a < messArr.size(); a++) {
                    if (messArr.get(a).getId() == startLoadFromMessageId) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    startLoadFromMessageId = 0;
                    return;
                }
                int startLoadFrom = startLoadFromMessageId;
                boolean needSelect = needSelectFromMessageId;
                clearChatData();
                startLoadFromMessageId = startLoadFrom;
                needSelectFromMessageId = needSelect;
            }

            loadsCount++;
            long did = (Long) args[0];
            int loadIndex = did == dialog_id ? 0 : 1;
            int count = (Integer) args[1];
            boolean isCache = (Boolean) args[3];
            int fnid = (Integer) args[4];
            int last_unread_date = (Integer) args[7];
            int load_type = (Integer) args[8];
            boolean wasUnread = false;
            if (fnid != 0) {
                first_unread_id = fnid;
                last_message_id = (Integer) args[5];
                unread_to_load = (Integer) args[6];
            } else if (startLoadFromMessageId != 0 && load_type == 3) {
                last_message_id = (Integer) args[5];
            }
            int newRowsCount = 0;

            forwardEndReached[loadIndex] = startLoadFromMessageId == 0 && last_message_id == 0;
            if ((load_type == 1 || load_type == 3) && loadIndex == 1) {
                endReached[0] = cacheEndReached[0] = true;
                forwardEndReached[0] = false;
                minMessageId[0] = 0;
            }

            if (loadsCount == 1 && messArr.size() > 20) {
                loadsCount++;
            }

            if (firstLoading) {
                if (!forwardEndReached[loadIndex]) {
                    messages.clear();
                    messagesByDays.clear();
                    for (int a = 0; a < 2; a++) {
                        messagesDict[a].clear();
                        if (currentEncryptedChat == null) {
                            maxMessageId[a] = Integer.MAX_VALUE;
                            minMessageId[a] = Integer.MIN_VALUE;
                        } else {
                            maxMessageId[a] = Integer.MIN_VALUE;
                            minMessageId[a] = Integer.MAX_VALUE;
                        }
                        maxDate[a] = Integer.MIN_VALUE;
                        minDate[a] = 0;
                    }
                }
                firstLoading = false;
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (parentLayout != null) {
                            parentLayout.resumeDelayedFragmentAnimation();
                        }
                    }
                });
            }

            if (load_type == 1) {
                Collections.reverse(messArr);
            }
            if (currentEncryptedChat == null) {
                MessagesQuery.loadReplyMessagesForMessages(messArr, dialog_id);
            }
            int approximateHeightSum = 0;
            for (int a = 0; a < messArr.size(); a++) {
                MessageObject obj = messArr.get(a);
                approximateHeightSum += obj.getApproximateHeight();
                if (currentUser != null) {
                    if (currentUser.self) {
                        obj.messageOwner.out = true;
                    }
                    if (currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                }
                if (messagesDict[loadIndex].containsKey(obj.getId())) {
                    continue;
                }
                if (loadIndex == 1) {
                    obj.setIsRead();
                }
                if (loadIndex == 0 && ChatObject.isChannel(currentChat) && obj.getId() == 1) {
                    endReached[loadIndex] = true;
                    cacheEndReached[loadIndex] = true;
                }
                if (obj.getId() > 0) {
                    maxMessageId[loadIndex] = Math.min(obj.getId(), maxMessageId[loadIndex]);
                    minMessageId[loadIndex] = Math.max(obj.getId(), minMessageId[loadIndex]);
                } else if (currentEncryptedChat != null) {
                    maxMessageId[loadIndex] = Math.max(obj.getId(), maxMessageId[loadIndex]);
                    minMessageId[loadIndex] = Math.min(obj.getId(), minMessageId[loadIndex]);
                }
                if (obj.messageOwner.date != 0) {
                    maxDate[loadIndex] = Math.max(maxDate[loadIndex], obj.messageOwner.date);
                    if (minDate[loadIndex] == 0 || obj.messageOwner.date < minDate[loadIndex]) {
                        minDate[loadIndex] = obj.messageOwner.date;
                    }
                }

                if (obj.type < 0 || loadIndex == 1
                        && obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                    continue;
                }

                if (!obj.isOut() && obj.isUnread()) {
                    wasUnread = true;
                }
                messagesDict[loadIndex].put(obj.getId(), obj);
                ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);

                if (dayArray == null) {
                    dayArray = new ArrayList<>();
                    messagesByDays.put(obj.dateKey, dayArray);
                    TLRPC.Message dateMsg = new TLRPC.Message();
                    dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
                    dateMsg.id = 0;
                    dateMsg.date = obj.messageOwner.date;
                    MessageObject dateObj = new MessageObject(dateMsg, null, false);
                    dateObj.type = 10;
                    dateObj.contentType = 1;
                    if (load_type == 1) {
                        messages.add(0, dateObj);
                    } else {
                        messages.add(dateObj);
                    }
                    newRowsCount++;
                }

                newRowsCount++;
                if (load_type == 1) {
                    dayArray.add(obj);
                    messages.add(0, obj);
                }

                if (load_type != 1) {
                    dayArray.add(obj);
                    messages.add(messages.size() - 1, obj);
                }

                if (obj.getId() == last_message_id) {
                    forwardEndReached[loadIndex] = true;
                }

                if (load_type == 2 && obj.getId() == first_unread_id) {
                    if (approximateHeightSum > AndroidUtilities.displaySize.y / 2 || !forwardEndReached[0]) {
                        TLRPC.Message dateMsg = new TLRPC.Message();
                        dateMsg.message = "";
                        dateMsg.id = 0;
                        MessageObject dateObj = new MessageObject(dateMsg, null, false);
                        dateObj.type = 6;
                        dateObj.contentType = 2;
                        messages.add(messages.size() - 1, dateObj);
                        unreadMessageObject = dateObj;
                        scrollToMessage = unreadMessageObject;
                        scrollToMessagePosition = -10000;
                        newRowsCount++;
                    }
                } else if (load_type == 3 && obj.getId() == startLoadFromMessageId) {
                    if (needSelectFromMessageId) {
                        highlightMessageId = obj.getId();
                    } else {
                        highlightMessageId = Integer.MAX_VALUE;
                    }
                    scrollToMessage = obj;
                    startLoadFromMessageId = 0;
                    if (scrollToMessagePosition == -10000) {
                        scrollToMessagePosition = -9000;
                    }
                }
            }
            if (load_type == 0 && newRowsCount == 0) {
                loadsCount--;
            }

            if (forwardEndReached[loadIndex] && loadIndex != 1) {
                first_unread_id = 0;
                last_message_id = 0;
            }

            if (loadsCount <= 2) {
                if (!isCache) {
                    updateSpamView();
                }
            }

            if (load_type == 1) {
                if (messArr.size() != count && !isCache) {
                    forwardEndReached[loadIndex] = true;
                    if (loadIndex != 1) {
                        first_unread_id = 0;
                        last_message_id = 0;
                        chatAdapter.notifyItemRemoved(chatAdapter.getItemCount() - 1);
                        newRowsCount--;
                    }
                    startLoadFromMessageId = 0;
                }
                if (newRowsCount > 0) {
                    int firstVisPos = chatLayoutManager.findLastVisibleItemPosition();
                    int top = 0;
                    if (firstVisPos != chatLayoutManager.getItemCount() - 1) {
                        firstVisPos = RecyclerView.NO_POSITION;
                    } else {
                        View firstVisView = chatLayoutManager.findViewByPosition(firstVisPos);
                        top = ((firstVisView == null) ? 0 : firstVisView.getTop())
                                - chatListView.getPaddingTop();
                    }
                    chatAdapter.notifyItemRangeInserted(chatAdapter.getItemCount() - 1, newRowsCount);
                    if (firstVisPos != RecyclerView.NO_POSITION) {
                        chatLayoutManager.scrollToPositionWithOffset(firstVisPos, top);
                    }
                }
                loadingForward = false;
            } else {
                if (messArr.size() < count && load_type != 3) {
                    if (isCache) {
                        if (currentEncryptedChat != null || isBroadcast) {
                            endReached[loadIndex] = true;
                        }
                        if (load_type != 2) {
                            cacheEndReached[loadIndex] = true;
                        }
                    } else if (load_type != 2) {
                        endReached[loadIndex] = true;// =TODO if < 7 from unread
                    }
                }
                loading = false;

                if (chatListView != null) {
                    if (first || scrollToTopOnResume || forceScrollToTop) {
                        forceScrollToTop = false;
                        chatAdapter.notifyDataSetChanged();
                        if (scrollToMessage != null) {
                            int yOffset;
                            if (scrollToMessagePosition == -9000) {
                                yOffset = Math.max(0,
                                        (chatListView.getHeight() - scrollToMessage.getApproximateHeight())
                                                / 2);
                            } else if (scrollToMessagePosition == -10000) {
                                yOffset = 0;
                            } else {
                                yOffset = scrollToMessagePosition;
                            }
                            if (!messages.isEmpty()) {
                                if (messages.get(messages.size() - 1) == scrollToMessage
                                        || messages.get(messages.size() - 2) == scrollToMessage) {
                                    chatLayoutManager.scrollToPositionWithOffset((chatAdapter.isBot ? 1 : 0),
                                            -chatListView.getPaddingTop() - AndroidUtilities.dp(7) + yOffset);
                                } else {
                                    chatLayoutManager.scrollToPositionWithOffset(
                                            chatAdapter.messagesStartRow + messages.size()
                                                    - messages.indexOf(scrollToMessage) - 1,
                                            -chatListView.getPaddingTop() - AndroidUtilities.dp(7) + yOffset);
                                }
                            }
                            chatListView.invalidate();
                            if (scrollToMessagePosition == -10000 || scrollToMessagePosition == -9000) {
                                showPagedownButton(true, true);
                            }
                            scrollToMessagePosition = -10000;
                            scrollToMessage = null;
                        } else {
                            moveScrollToLastMessage();
                        }
                    } else {
                        if (newRowsCount != 0) {
                            boolean end = false;
                            if (endReached[loadIndex]
                                    && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
                                end = true;
                                chatAdapter.notifyItemRangeChanged(chatAdapter.isBot ? 1 : 0, 2);
                            }
                            int firstVisPos = chatLayoutManager.findLastVisibleItemPosition();
                            View firstVisView = chatLayoutManager.findViewByPosition(firstVisPos);
                            int top = ((firstVisView == null) ? 0 : firstVisView.getTop())
                                    - chatListView.getPaddingTop();
                            if (newRowsCount - (end ? 1 : 0) > 0) {
                                chatAdapter.notifyItemRangeInserted((chatAdapter.isBot ? 2 : 1) + (end ? 0 : 1),
                                        newRowsCount - (end ? 1 : 0));
                            }
                            if (firstVisPos != -1) {
                                chatLayoutManager.scrollToPositionWithOffset(
                                        firstVisPos + newRowsCount - (end ? 1 : 0), top);
                            }
                        } else if (endReached[loadIndex]
                                && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
                            chatAdapter.notifyItemRemoved(chatAdapter.isBot ? 1 : 0);
                        }
                    }

                    if (paused) {
                        scrollToTopOnResume = true;
                        if (scrollToMessage != null) {
                            scrollToTopUnReadOnResume = true;
                        }
                    }

                    if (first) {
                        if (chatListView != null) {
                            chatListView.setEmptyView(emptyViewContainer);
                        }
                    }
                } else {
                    scrollToTopOnResume = true;
                    if (scrollToMessage != null) {
                        scrollToTopUnReadOnResume = true;
                    }
                }
            }

            if (first && messages.size() > 0) {
                if (loadIndex == 0) {
                    final boolean wasUnreadFinal = wasUnread;
                    final int last_unread_date_final = last_unread_date;
                    final int lastid = messages.get(0).getId();
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (last_message_id != 0) {
                                MessagesController.getInstance().markDialogAsRead(dialog_id, lastid,
                                        last_message_id, last_unread_date_final, wasUnreadFinal, false);
                            } else {
                                MessagesController.getInstance().markDialogAsRead(dialog_id, lastid,
                                        minMessageId[0], maxDate[0], wasUnreadFinal, false);
                            }
                        }
                    }, 700);
                }
                first = false;
            }
            if (messages.isEmpty() && currentEncryptedChat == null && currentUser != null && currentUser.bot
                    && botUser == null) {
                botUser = "";
                updateBottomOverlay();
            }

            if (newRowsCount == 0 && currentEncryptedChat != null && !endReached[0]) {
                first = true;
                if (chatListView != null) {
                    chatListView.setEmptyView(null);
                }
                if (emptyViewContainer != null) {
                    emptyViewContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
            }
            checkScrollForLoad(false);
        }
    } else if (id == NotificationCenter.emojiDidLoaded) {
        if (chatListView != null) {
            chatListView.invalidateViews();
        }
        if (replyObjectTextView != null) {
            replyObjectTextView.invalidate();
        }
        if (alertTextView != null) {
            alertTextView.invalidate();
        }
        if (pinnedMessageTextView != null) {
            pinnedMessageTextView.invalidate();
        }
        if (mentionListView != null) {
            mentionListView.invalidateViews();
        }
    } else if (id == NotificationCenter.updateInterfaces) {
        int updateMask = (Integer) args[0];
        if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0
                || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
            if (currentChat != null) {
                TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id);
                if (chat != null) {
                    currentChat = chat;
                }
            } else if (currentUser != null) {
                TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id);
                if (user != null) {
                    currentUser = user;
                }
            }
            updateTitle();
        }
        boolean updateSubtitle = false;
        if ((updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0
                || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0) {
            if (currentChat != null && avatarContainer != null) {
                avatarContainer.updateOnlineCount();
            }
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0
                || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0
                || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) {
            checkAndUpdateAvatar();
            updateVisibleRows();
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_CHANNEL) != 0 && ChatObject.isChannel(currentChat)) {
            TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id);
            if (chat == null) {
                return;
            }
            currentChat = chat;
            updateSubtitle = true;
            updateBottomOverlay();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setDialogId(dialog_id);
            }
        }
        if (avatarContainer != null && updateSubtitle) {
            avatarContainer.updateSubtitle();
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) {
            updateContactStatus();
        }
    } else if (id == NotificationCenter.didReceivedNewMessages) {
        long did = (Long) args[0];
        if (did == dialog_id) {

            boolean updateChat = false;
            boolean hasFromMe = false;
            ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
            if (currentEncryptedChat != null && arr.size() == 1) {
                MessageObject obj = arr.get(0);

                if (currentEncryptedChat != null && obj.isOut() && obj.messageOwner.action != null
                        && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                        && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL
                        && getParentActivity() != null) {
                    if (AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) < 17
                            && currentEncryptedChat.ttl > 0 && currentEncryptedChat.ttl <= 60) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
                        builder.setMessage(LocaleController.formatString("CompatibilityChat",
                                R.string.CompatibilityChat, currentUser.first_name, currentUser.first_name));
                        showDialog(builder.create());
                    }
                }
            }
            if (currentChat != null || inlineReturn != 0) {
                for (int a = 0; a < arr.size(); a++) {
                    MessageObject messageObject = arr.get(a);
                    if (currentChat != null) {
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser
                                && messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()
                                || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                        && messageObject.messageOwner.action.users
                                                .contains(UserConfig.getClientUserId())) {
                            TLRPC.Chat newChat = MessagesController.getInstance().getChat(currentChat.id);
                            if (newChat != null) {
                                currentChat = newChat;
                                checkActionBarMenu();
                                updateBottomOverlay();
                                if (avatarContainer != null) {
                                    avatarContainer.updateSubtitle();
                                }
                            }
                        } else if (messageObject.messageOwner.reply_to_msg_id != 0
                                && messageObject.replyMessageObject == null) {
                            messageObject.replyMessageObject = messagesDict[0]
                                    .get(messageObject.messageOwner.reply_to_msg_id);
                            if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
                                messageObject.generatePinMessageText(null, null);
                            } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                                messageObject.generateGameMessageText(null);
                            }
                        }
                    } else if (inlineReturn != 0) {
                        if (messageObject.messageOwner.reply_markup != null) {
                            for (int b = 0; b < messageObject.messageOwner.reply_markup.rows.size(); b++) {
                                TLRPC.TL_keyboardButtonRow row = messageObject.messageOwner.reply_markup.rows
                                        .get(b);
                                for (int c = 0; c < row.buttons.size(); c++) {
                                    TLRPC.KeyboardButton button = row.buttons.get(c);
                                    if (button instanceof TLRPC.TL_keyboardButtonSwitchInline) {
                                        processSwitchButton((TLRPC.TL_keyboardButtonSwitchInline) button);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            boolean reloadMegagroup = false;
            if (!forwardEndReached[0]) {
                int currentMaxDate = Integer.MIN_VALUE;
                int currentMinMsgId = Integer.MIN_VALUE;
                if (currentEncryptedChat != null) {
                    currentMinMsgId = Integer.MAX_VALUE;
                }
                boolean currentMarkAsRead = false;

                for (int a = 0; a < arr.size(); a++) {
                    MessageObject obj = arr.get(a);
                    if (currentUser != null && currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                    if (avatarContainer != null && currentEncryptedChat != null
                            && obj.messageOwner.action != null
                            && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                            && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
                        avatarContainer.setTime(
                                ((TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction).ttl_seconds);
                    }
                    if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        final Bundle bundle = new Bundle();
                        bundle.putInt("chat_id", obj.messageOwner.action.channel_id);
                        final BaseFragment lastFragment = parentLayout.fragmentsStack.size() > 0
                                ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1)
                                : null;
                        final int channel_id = obj.messageOwner.action.channel_id;
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                ActionBarLayout parentLayout = ChatActivity.this.parentLayout;
                                if (lastFragment != null) {
                                    NotificationCenter.getInstance().removeObserver(lastFragment,
                                            NotificationCenter.closeChats);
                                }
                                NotificationCenter.getInstance()
                                        .postNotificationName(NotificationCenter.closeChats);
                                parentLayout.presentFragment(new ChatActivity(bundle), true);
                                AndroidUtilities.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessagesController.getInstance().loadFullChat(channel_id, 0, true);
                                    }
                                }, 1000);
                            }
                        });
                        return;
                    } else if (currentChat != null && currentChat.megagroup
                            && (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                    || obj.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser)) {
                        reloadMegagroup = true;
                    }
                    if (obj.isOut() && obj.isSending()) {
                        scrollToLastMessage(false);
                        return;
                    }
                    if (obj.type < 0 || messagesDict[0].containsKey(obj.getId())) {
                        continue;
                    }
                    obj.checkLayout();
                    currentMaxDate = Math.max(currentMaxDate, obj.messageOwner.date);
                    if (obj.getId() > 0) {
                        currentMinMsgId = Math.max(obj.getId(), currentMinMsgId);
                        last_message_id = Math.max(last_message_id, obj.getId());
                    } else if (currentEncryptedChat != null) {
                        currentMinMsgId = Math.min(obj.getId(), currentMinMsgId);
                        last_message_id = Math.min(last_message_id, obj.getId());
                    }

                    if (!obj.isOut() && obj.isUnread()) {
                        unread_to_load++;
                        currentMarkAsRead = true;
                    }
                    if (obj.type == 10 || obj.type == 11) {
                        updateChat = true;
                    }
                }

                if (currentMarkAsRead) {
                    if (paused) {
                        readWhenResume = true;
                        readWithDate = currentMaxDate;
                        readWithMid = currentMinMsgId;
                    } else {
                        if (messages.size() > 0) {
                            MessagesController.getInstance().markDialogAsRead(dialog_id,
                                    messages.get(0).getId(), currentMinMsgId, currentMaxDate, true, false);
                        }
                    }
                }
                updateVisibleRows();
            } else {
                boolean markAsRead = false;
                boolean unreadUpdated = true;
                int oldCount = messages.size();
                int addedCount = 0;
                HashMap<String, ArrayList<MessageObject>> webpagesToReload = null;
                int placeToPaste = -1;
                for (int a = 0; a < arr.size(); a++) {
                    MessageObject obj = arr.get(a);
                    if (a == 0) {
                        if (obj.messageOwner.id < 0) {
                            placeToPaste = 0;
                        } else {
                            if (!messages.isEmpty()) {
                                int size = messages.size();
                                for (int b = 0; b < size; b++) {
                                    MessageObject lastMessage = messages.get(b);
                                    if (lastMessage.type >= 0 && lastMessage.messageOwner.date > 0) {
                                        if (lastMessage.messageOwner.id > 0 && obj.messageOwner.id > 0) {
                                            if (lastMessage.messageOwner.id < obj.messageOwner.id) {
                                                placeToPaste = b;
                                                break;
                                            }
                                        } else {
                                            if (lastMessage.messageOwner.date < obj.messageOwner.date) {
                                                placeToPaste = b;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (placeToPaste == -1 || placeToPaste > messages.size()) {
                                    placeToPaste = messages.size();
                                }
                            } else {
                                placeToPaste = 0;
                            }
                        }
                    }
                    if (currentUser != null && currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                    if (avatarContainer != null && currentEncryptedChat != null
                            && obj.messageOwner.action != null
                            && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                            && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
                        avatarContainer.setTime(
                                ((TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction).ttl_seconds);
                    }
                    if (obj.type < 0 || messagesDict[0].containsKey(obj.getId())) {
                        continue;
                    }
                    if (currentEncryptedChat != null
                            && obj.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage
                            && obj.messageOwner.media.webpage instanceof TLRPC.TL_webPageUrlPending) {
                        if (webpagesToReload == null) {
                            webpagesToReload = new HashMap<>();
                        }
                        ArrayList<MessageObject> arrayList = webpagesToReload
                                .get(obj.messageOwner.media.webpage.url);
                        if (arrayList == null) {
                            arrayList = new ArrayList<>();
                            webpagesToReload.put(obj.messageOwner.media.webpage.url, arrayList);
                        }
                        arrayList.add(obj);
                    }
                    obj.checkLayout();
                    if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        final Bundle bundle = new Bundle();
                        bundle.putInt("chat_id", obj.messageOwner.action.channel_id);
                        final BaseFragment lastFragment = parentLayout.fragmentsStack.size() > 0
                                ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1)
                                : null;
                        final int channel_id = obj.messageOwner.action.channel_id;
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                ActionBarLayout parentLayout = ChatActivity.this.parentLayout;
                                if (lastFragment != null) {
                                    NotificationCenter.getInstance().removeObserver(lastFragment,
                                            NotificationCenter.closeChats);
                                }
                                NotificationCenter.getInstance()
                                        .postNotificationName(NotificationCenter.closeChats);
                                parentLayout.presentFragment(new ChatActivity(bundle), true);
                                AndroidUtilities.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessagesController.getInstance().loadFullChat(channel_id, 0, true);
                                    }
                                }, 1000);
                            }
                        });
                        return;
                    } else if (currentChat != null && currentChat.megagroup
                            && (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                    || obj.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser)) {
                        reloadMegagroup = true;
                    }
                    if (minDate[0] == 0 || obj.messageOwner.date < minDate[0]) {
                        minDate[0] = obj.messageOwner.date;
                    }

                    if (obj.isOut()) {
                        removeUnreadPlane();
                        hasFromMe = true;
                    }

                    if (obj.getId() > 0) {
                        maxMessageId[0] = Math.min(obj.getId(), maxMessageId[0]);
                        minMessageId[0] = Math.max(obj.getId(), minMessageId[0]);
                    } else if (currentEncryptedChat != null) {
                        maxMessageId[0] = Math.max(obj.getId(), maxMessageId[0]);
                        minMessageId[0] = Math.min(obj.getId(), minMessageId[0]);
                    }
                    maxDate[0] = Math.max(maxDate[0], obj.messageOwner.date);
                    messagesDict[0].put(obj.getId(), obj);
                    ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);
                    if (dayArray == null) {
                        dayArray = new ArrayList<>();
                        messagesByDays.put(obj.dateKey, dayArray);
                        TLRPC.Message dateMsg = new TLRPC.Message();
                        dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
                        dateMsg.id = 0;
                        dateMsg.date = obj.messageOwner.date;
                        MessageObject dateObj = new MessageObject(dateMsg, null, false);
                        dateObj.type = 10;
                        dateObj.contentType = 1;
                        messages.add(placeToPaste, dateObj);
                        addedCount++;
                    }
                    if (!obj.isOut()) {
                        if (paused && placeToPaste == 0) {
                            if (!scrollToTopUnReadOnResume && unreadMessageObject != null) {
                                removeMessageObject(unreadMessageObject);
                                if (placeToPaste > 0) {
                                    placeToPaste--;
                                }
                                unreadMessageObject = null;
                            }
                            if (unreadMessageObject == null) {
                                TLRPC.Message dateMsg = new TLRPC.Message();
                                dateMsg.message = "";
                                dateMsg.id = 0;
                                MessageObject dateObj = new MessageObject(dateMsg, null, false);
                                dateObj.type = 6;
                                dateObj.contentType = 2;
                                messages.add(0, dateObj);
                                unreadMessageObject = dateObj;
                                scrollToMessage = unreadMessageObject;
                                scrollToMessagePosition = -10000;
                                unreadUpdated = false;
                                unread_to_load = 0;
                                scrollToTopUnReadOnResume = true;
                                addedCount++;
                            }
                        }
                        if (unreadMessageObject != null) {
                            unread_to_load++;
                            unreadUpdated = true;
                        }
                        if (obj.isUnread()) {
                            if (!paused) {
                                obj.setIsRead();
                            }
                            markAsRead = true;
                        }
                    }

                    dayArray.add(0, obj);
                    if (placeToPaste > messages.size()) {
                        placeToPaste = messages.size();
                    }
                    messages.add(placeToPaste, obj);
                    addedCount++;
                    newUnreadMessageCount++;
                    if (obj.type == 10 || obj.type == 11) {
                        updateChat = true;
                    }
                }
                if (webpagesToReload != null) {
                    MessagesController.getInstance().reloadWebPages(dialog_id, webpagesToReload);
                }

                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
                if (chatAdapter != null) {
                    if (unreadUpdated) {
                        chatAdapter.updateRowWithMessageObject(unreadMessageObject);
                    }
                    if (addedCount != 0) {
                        chatAdapter.notifyItemRangeInserted(chatAdapter.getItemCount() - placeToPaste,
                                addedCount);
                    }
                } else {
                    scrollToTopOnResume = true;
                }

                if (chatListView != null && chatAdapter != null) {
                    int lastVisible = chatLayoutManager.findLastVisibleItemPosition();
                    if (lastVisible == RecyclerView.NO_POSITION) {
                        lastVisible = 0;
                    }
                    if (endReached[0]) {
                        lastVisible++;
                    }
                    if (chatAdapter.isBot) {
                        oldCount++;
                    }
                    if (lastVisible >= oldCount || hasFromMe) {
                        newUnreadMessageCount = 0;
                        if (!firstLoading) {
                            if (paused) {
                                scrollToTopOnResume = true;
                            } else {
                                forceScrollToTop = true;
                                moveScrollToLastMessage();
                            }
                        }
                    } else {
                        if (newUnreadMessageCount != 0 && pagedownButtonCounter != null) {
                            pagedownButtonCounter.setVisibility(View.VISIBLE);
                            pagedownButtonCounter.setText(String.format("%d", newUnreadMessageCount));
                        }
                        showPagedownButton(true, true);
                    }
                } else {
                    scrollToTopOnResume = true;
                }

                if (markAsRead) {
                    if (paused) {
                        readWhenResume = true;
                        readWithDate = maxDate[0];
                        readWithMid = minMessageId[0];
                    } else {
                        MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).getId(),
                                minMessageId[0], maxDate[0], true, false);
                    }
                }
            }
            if (!messages.isEmpty() && botUser != null && botUser.length() == 0) {
                botUser = null;
                updateBottomOverlay();
            }
            if (updateChat) {
                updateTitle();
                checkAndUpdateAvatar();
            }
            if (reloadMegagroup) {
                MessagesController.getInstance().loadFullChat(currentChat.id, 0, true);
            }
        }
    } else if (id == NotificationCenter.closeChats) {
        if (args != null && args.length > 0) {
            long did = (Long) args[0];
            if (did == dialog_id) {
                finishFragment();
            }
        } else {
            removeSelfFromStack();
        }
    } else if (id == NotificationCenter.messagesRead) {
        SparseArray<Long> inbox = (SparseArray<Long>) args[0];
        SparseArray<Long> outbox = (SparseArray<Long>) args[1];
        boolean updated = false;
        for (int b = 0; b < inbox.size(); b++) {
            int key = inbox.keyAt(b);
            long messageId = inbox.get(key);
            if (key != dialog_id) {
                continue;
            }
            for (int a = 0; a < messages.size(); a++) {
                MessageObject obj = messages.get(a);
                if (!obj.isOut() && obj.getId() > 0 && obj.getId() <= (int) messageId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    updated = true;
                }
            }
            break;
        }
        for (int b = 0; b < outbox.size(); b++) {
            int key = outbox.keyAt(b);
            int messageId = (int) ((long) outbox.get(key));
            if (key != dialog_id) {
                continue;
            }
            for (int a = 0; a < messages.size(); a++) {
                MessageObject obj = messages.get(a);
                if (obj.isOut() && obj.getId() > 0 && obj.getId() <= messageId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    updated = true;
                }
            }
            break;
        }
        if (updated) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.messagesDeleted) {
        ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
        int channelId = (Integer) args[1];
        int loadIndex = 0;
        if (ChatObject.isChannel(currentChat)) {
            if (channelId == 0 && mergeDialogId != 0) {
                loadIndex = 1;
            } else if (channelId == currentChat.id) {
                loadIndex = 0;
            } else {
                return;
            }
        } else if (channelId != 0) {
            return;
        }
        boolean updated = false;
        for (int a = 0; a < markAsDeletedMessages.size(); a++) {
            Integer ids = markAsDeletedMessages.get(a);
            MessageObject obj = messagesDict[loadIndex].get(ids);
            if (loadIndex == 0 && info != null && info.pinned_msg_id == ids) {
                pinnedMessageObject = null;
                info.pinned_msg_id = 0;
                MessagesStorage.getInstance().updateChannelPinnedMessage(channelId, 0);
                updatePinnedMessageView(true);
            }
            if (obj != null) {
                int index = messages.indexOf(obj);
                if (index != -1) {
                    messages.remove(index);
                    messagesDict[loadIndex].remove(ids);
                    ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey);
                    if (dayArr != null) {
                        dayArr.remove(obj);
                        if (dayArr.isEmpty()) {
                            messagesByDays.remove(obj.dateKey);
                            if (index >= 0 && index < messages.size()) {
                                messages.remove(index);
                            }
                        }
                    }
                    updated = true;
                }
            }
        }
        if (messages.isEmpty()) {
            if (!endReached[0] && !loading) {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
                if (chatListView != null) {
                    chatListView.setEmptyView(null);
                }
                if (currentEncryptedChat == null) {
                    maxMessageId[0] = maxMessageId[1] = Integer.MAX_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MIN_VALUE;
                } else {
                    maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE;
                }
                maxDate[0] = maxDate[1] = Integer.MIN_VALUE;
                minDate[0] = minDate[1] = 0;
                waitingForLoad.add(lastLoadIndex);
                MessagesController.getInstance().loadMessages(dialog_id, 30, 0, !cacheEndReached[0], minDate[0],
                        classGuid, 0, 0, ChatObject.isChannel(currentChat), lastLoadIndex++);
                loading = true;
            } else {
                if (botButtons != null) {
                    botButtons = null;
                    if (chatActivityEnterView != null) {
                        chatActivityEnterView.setButtons(null, false);
                    }
                }
                if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
                    botUser = "";
                    updateBottomOverlay();
                }
            }
        }
        if (updated && chatAdapter != null) {
            removeUnreadPlane();
            chatAdapter.notifyDataSetChanged();
        }
    } else if (id == NotificationCenter.messageReceivedByServer) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            Integer newMsgId = (Integer) args[1];
            if (!newMsgId.equals(msgId) && messagesDict[0].containsKey(newMsgId)) {
                MessageObject removed = messagesDict[0].remove(msgId);
                if (removed != null) {
                    int index = messages.indexOf(removed);
                    messages.remove(index);
                    ArrayList<MessageObject> dayArr = messagesByDays.get(removed.dateKey);
                    dayArr.remove(obj);
                    if (dayArr.isEmpty()) {
                        messagesByDays.remove(obj.dateKey);
                        if (index >= 0 && index < messages.size()) {
                            messages.remove(index);
                        }
                    }
                    if (chatAdapter != null) {
                        chatAdapter.notifyDataSetChanged();
                    }
                }
                return;
            }
            TLRPC.Message newMsgObj = (TLRPC.Message) args[2];
            boolean mediaUpdated = false;
            boolean updatedForward = false;
            if (newMsgObj != null) {
                try {
                    updatedForward = obj.isForwarded()
                            && (obj.messageOwner.reply_markup == null && newMsgObj.reply_markup != null
                                    || !obj.messageOwner.message.equals(newMsgObj.message));
                    mediaUpdated = updatedForward
                            || obj.messageOwner.params != null
                                    && obj.messageOwner.params.containsKey("query_id")
                            || newMsgObj.media != null && obj.messageOwner.media != null
                                    && !newMsgObj.media.getClass().equals(obj.messageOwner.media.getClass());
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                obj.messageOwner = newMsgObj;
                obj.generateThumbs(true);
                obj.setType();
                if (newMsgObj.media instanceof TLRPC.TL_messageMediaGame) {
                    obj.applyNewText();
                }
            }
            if (updatedForward) {
                obj.measureInlineBotButtons();
            }
            messagesDict[0].remove(msgId);
            messagesDict[0].put(newMsgId, obj);
            obj.messageOwner.id = newMsgId;
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            obj.forceUpdate = mediaUpdated;
            ArrayList<MessageObject> messArr = new ArrayList<>();
            messArr.add(obj);
            if (currentEncryptedChat == null) {
                MessagesQuery.loadReplyMessagesForMessages(messArr, dialog_id);
            }
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj);
            }
            if (chatLayoutManager != null) {
                if (mediaUpdated && chatLayoutManager.findLastVisibleItemPosition() >= messages.size() - 1) {
                    moveScrollToLastMessage();
                }
            }
            NotificationsController.getInstance().playOutChatSound();
        }
    } else if (id == NotificationCenter.messageReceivedByAck) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj);
            }
        }
    } else if (id == NotificationCenter.messageSendError) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.chatInfoDidLoaded) {
        TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0];
        if (currentChat != null && chatFull.id == currentChat.id) {
            if (chatFull instanceof TLRPC.TL_channelFull) {
                if (currentChat.megagroup) {
                    int lastDate = 0;
                    if (chatFull.participants != null) {
                        for (int a = 0; a < chatFull.participants.participants.size(); a++) {
                            lastDate = Math.max(chatFull.participants.participants.get(a).date, lastDate);
                        }
                    }
                    if (lastDate == 0 || Math.abs(System.currentTimeMillis() / 1000 - lastDate) > 60 * 60) {
                        MessagesController.getInstance().loadChannelParticipants(currentChat.id);
                    }
                }
                if (chatFull.participants == null && info != null) {
                    chatFull.participants = info.participants;
                }
            }
            info = chatFull;
            if (mentionsAdapter != null) {
                mentionsAdapter.setChatInfo(info);
            }
            if (args[3] instanceof MessageObject) {
                pinnedMessageObject = (MessageObject) args[3];
                updatePinnedMessageView(false);
            } else {
                updatePinnedMessageView(true);
            }
            if (avatarContainer != null) {
                avatarContainer.updateOnlineCount();
                avatarContainer.updateSubtitle();
            }
            if (isBroadcast) {
                SendMessagesHelper.getInstance().setCurrentChatInfo(info);
            }
            if (info instanceof TLRPC.TL_chatFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = false;
                for (int a = 0; a < info.participants.participants.size(); a++) {
                    TLRPC.ChatParticipant participant = info.participants.participants.get(a);
                    TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id);
                    if (user != null && user.bot) {
                        URLSpanBotCommand.enabled = true;
                        botsCount++;
                        BotQuery.loadBotInfo(user.id, true, classGuid);
                    }
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
            } else if (info instanceof TLRPC.TL_channelFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = !info.bot_info.isEmpty();
                botsCount = info.bot_info.size();
                for (int a = 0; a < info.bot_info.size(); a++) {
                    TLRPC.BotInfo bot = info.bot_info.get(a);
                    if (!bot.commands.isEmpty() && (!ChatObject.isChannel(currentChat)
                            || currentChat != null && currentChat.megagroup)) {
                        hasBotsCommands = true;
                    }
                    botInfo.put(bot.user_id, bot);
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
                if (mentionsAdapter != null && (!ChatObject.isChannel(currentChat)
                        || currentChat != null && currentChat.megagroup)) {
                    mentionsAdapter.setBotInfo(botInfo);
                }
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setBotsCount(botsCount);
            }
            if (ChatObject.isChannel(currentChat) && mergeDialogId == 0 && info.migrated_from_chat_id != 0) {
                mergeDialogId = -info.migrated_from_chat_id;
                maxMessageId[1] = info.migrated_from_max_id;
                if (chatAdapter != null) {
                    chatAdapter.notifyDataSetChanged();
                }
            }
        }
    } else if (id == NotificationCenter.chatInfoCantLoad) {
        int chatId = (Integer) args[0];
        if (currentChat != null && currentChat.id == chatId) {
            int reason = (Integer) args[1];
            if (getParentActivity() == null || closeChatDialog != null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            if (reason == 0) {
                builder.setMessage(
                        LocaleController.getString("ChannelCantOpenPrivate", R.string.ChannelCantOpenPrivate));
            } else if (reason == 1) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenNa", R.string.ChannelCantOpenNa));
            } else if (reason == 2) {
                builder.setMessage(
                        LocaleController.getString("ChannelCantOpenBanned", R.string.ChannelCantOpenBanned));
            }
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), null);
            showDialog(closeChatDialog = builder.create());

            loading = false;
            if (progressView != null) {
                progressView.setVisibility(View.INVISIBLE);
            }
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.contactsDidLoaded) {
        updateContactStatus();
        if (avatarContainer != null) {
            avatarContainer.updateSubtitle();
        }
    } else if (id == NotificationCenter.encryptedChatUpdated) {
        TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0];
        if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) {
            currentEncryptedChat = chat;
            updateContactStatus();
            updateSecretStatus();
            initStickers();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setNeedBotContext(
                        !chatActivityEnterView.isEditingMessage() && (currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46));
            }
        }
    } else if (id == NotificationCenter.messagesReadEncrypted) {
        int encId = (Integer) args[0];
        if (currentEncryptedChat != null && currentEncryptedChat.id == encId) {
            int date = (Integer) args[1];
            for (MessageObject obj : messages) {
                if (!obj.isOut()) {
                    continue;
                } else if (obj.isOut() && !obj.isUnread()) {
                    break;
                }
                if (obj.messageOwner.date - 1 <= date) {
                    obj.setIsRead();
                }
            }
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.audioDidReset || id == NotificationCenter.audioPlayStateChanged) {
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
            count = mentionListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = mentionListView.getChildAt(a);
                if (view instanceof ContextLinkCell) {
                    ContextLinkCell cell = (ContextLinkCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.audioProgressDidChanged) {
        Integer mid = (Integer) args[0];
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    if (cell.getMessageObject() != null && cell.getMessageObject().getId() == mid) {
                        MessageObject playing = cell.getMessageObject();
                        MessageObject player = MediaController.getInstance().getPlayingMessageObject();
                        if (player != null) {
                            playing.audioProgress = player.audioProgress;
                            playing.audioProgressSec = player.audioProgressSec;
                            cell.updateAudioProgress();
                        }
                        break;
                    }
                }
            }
        }
    } else if (id == NotificationCenter.removeAllMessagesFromDialog) {
        long did = (Long) args[0];
        if (dialog_id == did) {
            messages.clear();
            waitingForLoad.clear();
            messagesByDays.clear();
            for (int a = 1; a >= 0; a--) {
                messagesDict[a].clear();
                if (currentEncryptedChat == null) {
                    maxMessageId[a] = Integer.MAX_VALUE;
                    minMessageId[a] = Integer.MIN_VALUE;
                } else {
                    maxMessageId[a] = Integer.MIN_VALUE;
                    minMessageId[a] = Integer.MAX_VALUE;
                }
                maxDate[a] = Integer.MIN_VALUE;
                minDate[a] = 0;
                selectedMessagesIds[a].clear();
                selectedMessagesCanCopyIds[a].clear();
            }
            cantDeleteMessagesCount = 0;
            actionBar.hideActionMode();
            updatePinnedMessageView(true);

            if (botButtons != null) {
                botButtons = null;
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.setButtons(null, false);
                }
            }
            if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
                botUser = "";
                updateBottomOverlay();
            }
            if ((Boolean) args[1]) {
                if (chatAdapter != null) {
                    progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
                    chatListView.setEmptyView(null);
                }
                for (int a = 0; a < 2; a++) {
                    endReached[a] = false;
                    cacheEndReached[a] = false;
                    forwardEndReached[a] = true;
                }
                first = true;
                firstLoading = true;
                loading = true;
                startLoadFromMessageId = 0;
                needSelectFromMessageId = false;
                waitingForLoad.add(lastLoadIndex);
                MessagesController.getInstance().loadMessages(dialog_id, AndroidUtilities.isTablet() ? 30 : 20,
                        0, true, 0, classGuid, 2, 0, ChatObject.isChannel(currentChat), lastLoadIndex++);
            } else {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                    chatListView.setEmptyView(emptyViewContainer);
                }
            }

            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.screenshotTook) {
        updateInformationForScreenshotDetector();
    } else if (id == NotificationCenter.blockedUsersDidLoaded) {
        if (currentUser != null) {
            boolean oldValue = userBlocked;
            userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id);
            if (oldValue != userBlocked) {
                updateBottomOverlay();
            }
        }
    } else if (id == NotificationCenter.FileNewChunkAvailable) {
        MessageObject messageObject = (MessageObject) args[0];
        long finalSize = (Long) args[2];
        if (finalSize != 0 && dialog_id == messageObject.getDialogId()) {
            MessageObject currentObject = messagesDict[0].get(messageObject.getId());
            if (currentObject != null) {
                currentObject.messageOwner.media.document.size = (int) finalSize;
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.didCreatedNewDeleteTask) {
        SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[0];
        boolean changed = false;
        for (int i = 0; i < mids.size(); i++) {
            int key = mids.keyAt(i);
            ArrayList<Integer> arr = mids.get(key);
            for (Integer mid : arr) {
                MessageObject messageObject = messagesDict[0].get(mid);
                if (messageObject != null) {
                    messageObject.messageOwner.destroyTime = key;
                    changed = true;
                }
            }
        }
        if (changed) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.audioDidStarted) {
        MessageObject messageObject = (MessageObject) args[0];
        sendSecretMessageRead(messageObject);
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject1 = cell.getMessageObject();
                    if (messageObject1 != null && (messageObject1.isVoice() || messageObject1.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.updateMessageMedia) {
        MessageObject messageObject = (MessageObject) args[0];
        MessageObject existMessageObject = messagesDict[0].get(messageObject.getId());
        if (existMessageObject != null) {
            existMessageObject.messageOwner.media = messageObject.messageOwner.media;
            existMessageObject.messageOwner.attachPath = messageObject.messageOwner.attachPath;
            existMessageObject.generateThumbs(false);
        }
        updateVisibleRows();
    } else if (id == NotificationCenter.replaceMessagesObjects) {
        long did = (long) args[0];
        if (did != dialog_id && did != mergeDialogId) {
            return;
        }
        int loadIndex = did == dialog_id ? 0 : 1;
        boolean changed = false;
        boolean mediaUpdated = false;
        ArrayList<MessageObject> messageObjects = (ArrayList<MessageObject>) args[1];
        for (int a = 0; a < messageObjects.size(); a++) {
            MessageObject messageObject = messageObjects.get(a);
            MessageObject old = messagesDict[loadIndex].get(messageObject.getId());
            if (pinnedMessageObject != null && pinnedMessageObject.getId() == messageObject.getId()) {
                pinnedMessageObject = messageObject;
                updatePinnedMessageView(true);
            }
            if (old != null) {
                if (messageObject.type >= 0) {
                    if (!mediaUpdated
                            && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
                        mediaUpdated = true;
                    }
                    if (old.replyMessageObject != null) {
                        messageObject.replyMessageObject = old.replyMessageObject;
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                            messageObject.generateGameMessageText(null);
                        }
                    }
                    messageObject.messageOwner.attachPath = old.messageOwner.attachPath;
                    messageObject.attachPathExists = old.attachPathExists;
                    messageObject.mediaExists = old.mediaExists;
                    messagesDict[loadIndex].put(old.getId(), messageObject);
                } else {
                    messagesDict[loadIndex].remove(old.getId());
                }
                int index = messages.indexOf(old);
                if (index >= 0) {
                    ArrayList<MessageObject> dayArr = messagesByDays.get(old.dateKey);
                    int index2 = -1;
                    if (dayArr != null) {
                        index2 = dayArr.indexOf(old);
                    }
                    if (messageObject.type >= 0) {
                        messages.set(index, messageObject);
                        if (chatAdapter != null) {
                            chatAdapter.notifyItemChanged(
                                    chatAdapter.messagesStartRow + messages.size() - index - 1);
                        }
                        if (index2 >= 0) {
                            dayArr.set(index2, messageObject);
                        }
                    } else {
                        messages.remove(index);
                        if (chatAdapter != null) {
                            chatAdapter.notifyItemRemoved(
                                    chatAdapter.messagesStartRow + messages.size() - index - 1);
                        }
                        if (index2 >= 0) {
                            dayArr.remove(index2);
                            if (dayArr.isEmpty()) {
                                messagesByDays.remove(old.dateKey);
                                messages.remove(index);
                                chatAdapter.notifyItemRemoved(chatAdapter.messagesStartRow + messages.size());
                            }
                        }
                    }
                    changed = true;
                }
            }
        }
        if (changed && chatLayoutManager != null) {
            if (mediaUpdated && chatLayoutManager.findLastVisibleItemPosition() >= messages.size()
                    - (chatAdapter.isBot ? 2 : 1)) {
                moveScrollToLastMessage();
            }
        }
    } else if (id == NotificationCenter.notificationsSettingsUpdated) {
        updateTitleIcons();
        if (ChatObject.isChannel(currentChat)) {
            updateBottomOverlay();
        }
    } else if (id == NotificationCenter.didLoadedReplyMessages) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.didLoadedPinnedMessage) {
        MessageObject message = (MessageObject) args[0];
        if (message.getDialogId() == dialog_id && info != null && info.pinned_msg_id == message.getId()) {
            pinnedMessageObject = message;
            loadingPinnedMessage = 0;
            updatePinnedMessageView(true);
        }
    } else if (id == NotificationCenter.didReceivedWebpages) {
        ArrayList<TLRPC.Message> arrayList = (ArrayList<TLRPC.Message>) args[0];
        boolean updated = false;
        for (int a = 0; a < arrayList.size(); a++) {
            TLRPC.Message message = arrayList.get(a);
            long did = MessageObject.getDialogId(message);
            if (did != dialog_id && did != mergeDialogId) {
                continue;
            }
            MessageObject currentMessage = messagesDict[did == dialog_id ? 0 : 1].get(message.id);
            if (currentMessage != null) {
                currentMessage.messageOwner.media = new TLRPC.TL_messageMediaWebPage();
                currentMessage.messageOwner.media.webpage = message.media.webpage;
                currentMessage.generateThumbs(true);
                updated = true;
            }
        }
        if (updated) {
            updateVisibleRows();
            if (chatLayoutManager != null
                    && chatLayoutManager.findLastVisibleItemPosition() >= messages.size() - 1) {
                moveScrollToLastMessage();
            }
        }
    } else if (id == NotificationCenter.didReceivedWebpagesInUpdates) {
        if (foundWebPage != null) {
            HashMap<Long, TLRPC.WebPage> hashMap = (HashMap<Long, TLRPC.WebPage>) args[0];
            for (TLRPC.WebPage webPage : hashMap.values()) {
                if (webPage.id == foundWebPage.id) {
                    showReplyPanel(!(webPage instanceof TLRPC.TL_webPageEmpty), null, null, webPage, false,
                            true);
                    break;
                }
            }
        }
    } else if (id == NotificationCenter.messagesReadContent) {
        ArrayList<Long> arrayList = (ArrayList<Long>) args[0];
        boolean updated = false;
        for (int a = 0; a < arrayList.size(); a++) {
            long mid = arrayList.get(a);
            MessageObject currentMessage = messagesDict[mergeDialogId == 0 ? 0 : 1].get((int) mid);
            if (currentMessage != null) {
                currentMessage.setContentIsRead();
                updated = true;
            }
        }
        if (updated) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.botInfoDidLoaded) {
        int guid = (Integer) args[1];
        if (classGuid == guid) {
            TLRPC.BotInfo info = (TLRPC.BotInfo) args[0];
            if (currentEncryptedChat == null) {
                if (!info.commands.isEmpty() && !ChatObject.isChannel(currentChat)) {
                    hasBotsCommands = true;
                }
                botInfo.put(info.user_id, info);
                if (chatAdapter != null) {
                    chatAdapter.notifyItemChanged(0);
                }
                if (mentionsAdapter != null && (!ChatObject.isChannel(currentChat)
                        || currentChat != null && currentChat.megagroup)) {
                    mentionsAdapter.setBotInfo(botInfo);
                }
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
                }
            }
            updateBotButtons();
        }
    } else if (id == NotificationCenter.botKeyboardDidLoaded) {
        if (dialog_id == (Long) args[1]) {
            TLRPC.Message message = (TLRPC.Message) args[0];
            if (message != null && !userBlocked) {
                botButtons = new MessageObject(message, null, false);
                if (chatActivityEnterView != null) {
                    if (botButtons.messageOwner.reply_markup instanceof TLRPC.TL_replyKeyboardForceReply) {
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        if (preferences.getInt("answered_" + dialog_id, 0) != botButtons.getId()
                                && (replyingMessageObject == null
                                        || chatActivityEnterView.getFieldText() == null)) {
                            botReplyButtons = botButtons;
                            chatActivityEnterView.setButtons(botButtons);
                            showReplyPanel(true, botButtons, null, null, false, true);
                        }
                    } else {
                        if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
                            botReplyButtons = null;
                            showReplyPanel(false, null, null, null, false, true);
                        }
                        chatActivityEnterView.setButtons(botButtons);
                    }
                }
            } else {
                botButtons = null;
                if (chatActivityEnterView != null) {
                    if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
                        botReplyButtons = null;
                        showReplyPanel(false, null, null, null, false, true);
                    }
                    chatActivityEnterView.setButtons(botButtons);
                }
            }
        }
    } else if (id == NotificationCenter.chatSearchResultsAvailable) {
        if (classGuid == (Integer) args[0]) {
            int messageId = (Integer) args[1];
            long did = (Long) args[3];
            if (messageId != 0) {
                scrollToMessageId(messageId, 0, true, did == dialog_id ? 0 : 1);
            }
            updateSearchButtons((Integer) args[2], (Integer) args[4], (Integer) args[5]);
        }
    } else if (id == NotificationCenter.didUpdatedMessagesViews) {
        SparseArray<SparseIntArray> channelViews = (SparseArray<SparseIntArray>) args[0];
        SparseIntArray array = channelViews.get((int) dialog_id);
        if (array != null) {
            boolean updated = false;
            for (int a = 0; a < array.size(); a++) {
                int messageId = array.keyAt(a);
                MessageObject messageObject = messagesDict[0].get(messageId);
                if (messageObject != null) {
                    int newValue = array.get(messageId);
                    if (newValue > messageObject.messageOwner.views) {
                        messageObject.messageOwner.views = newValue;
                        updated = true;
                    }
                }
            }
            if (updated) {
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.peerSettingsDidLoaded) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            updateSpamView();
        }
    } else if (id == NotificationCenter.newDraftReceived) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            applyDraftMaybe(true);
        }
    }
}

From source file:kr.wdream.ui.ChatActivity.java

@Override
public void didReceivedNotification(int id, final Object... args) {
    if (id == NotificationCenter.messagesDidLoaded) {
        int guid = (Integer) args[10];
        if (guid == classGuid) {
            if (!openAnimationEnded) {
                NotificationCenter.getInstance().setAllowedNotificationsDutingAnimation(new int[] {
                        NotificationCenter.chatInfoDidLoaded, NotificationCenter.dialogsNeedReload,
                        NotificationCenter.closeChats,
                        NotificationCenter.botKeyboardDidLoaded/*, NotificationCenter.botInfoDidLoaded*/ });
            }/*from   w  ww . j  ava2 s.co  m*/
            int queryLoadIndex = (Integer) args[11];
            int index = waitingForLoad.indexOf(queryLoadIndex);
            if (index == -1) {
                return;
            } else {
                waitingForLoad.remove(index);
            }
            ArrayList<MessageObject> messArr = (ArrayList<MessageObject>) args[2];
            if (waitingForReplyMessageLoad) {
                boolean found = false;
                for (int a = 0; a < messArr.size(); a++) {
                    if (messArr.get(a).getId() == startLoadFromMessageId) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    startLoadFromMessageId = 0;
                    return;
                }
                int startLoadFrom = startLoadFromMessageId;
                boolean needSelect = needSelectFromMessageId;
                clearChatData();
                startLoadFromMessageId = startLoadFrom;
                needSelectFromMessageId = needSelect;
            }

            loadsCount++;
            long did = (Long) args[0];
            int loadIndex = did == dialog_id ? 0 : 1;
            int count = (Integer) args[1];
            boolean isCache = (Boolean) args[3];
            int fnid = (Integer) args[4];
            int last_unread_date = (Integer) args[7];
            int load_type = (Integer) args[8];
            boolean wasUnread = false;
            if (fnid != 0) {
                first_unread_id = fnid;
                last_message_id = (Integer) args[5];
                unread_to_load = (Integer) args[6];
            } else if (startLoadFromMessageId != 0 && load_type == 3) {
                last_message_id = (Integer) args[5];
            }
            int newRowsCount = 0;

            forwardEndReached[loadIndex] = startLoadFromMessageId == 0 && last_message_id == 0;
            if ((load_type == 1 || load_type == 3) && loadIndex == 1) {
                endReached[0] = cacheEndReached[0] = true;
                forwardEndReached[0] = false;
                minMessageId[0] = 0;
            }

            if (loadsCount == 1 && messArr.size() > 20) {
                loadsCount++;
            }

            if (firstLoading) {
                if (!forwardEndReached[loadIndex]) {
                    messages.clear();
                    messagesByDays.clear();
                    for (int a = 0; a < 2; a++) {
                        messagesDict[a].clear();
                        if (currentEncryptedChat == null) {
                            maxMessageId[a] = Integer.MAX_VALUE;
                            minMessageId[a] = Integer.MIN_VALUE;
                        } else {
                            maxMessageId[a] = Integer.MIN_VALUE;
                            minMessageId[a] = Integer.MAX_VALUE;
                        }
                        maxDate[a] = Integer.MIN_VALUE;
                        minDate[a] = 0;
                    }
                }
                firstLoading = false;
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (parentLayout != null) {
                            parentLayout.resumeDelayedFragmentAnimation();
                        }
                    }
                });
            }

            if (load_type == 1) {
                Collections.reverse(messArr);
            }
            if (currentEncryptedChat == null) {
                MessagesQuery.loadReplyMessagesForMessages(messArr, dialog_id);
            }
            int approximateHeightSum = 0;
            for (int a = 0; a < messArr.size(); a++) {
                MessageObject obj = messArr.get(a);
                approximateHeightSum += obj.getApproximateHeight();
                if (currentUser != null) {
                    if (currentUser.self) {
                        obj.messageOwner.out = true;
                    }
                    if (currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                }
                if (messagesDict[loadIndex].containsKey(obj.getId())) {
                    continue;
                }
                if (loadIndex == 1) {
                    obj.setIsRead();
                }
                if (loadIndex == 0 && ChatObject.isChannel(currentChat) && obj.getId() == 1) {
                    endReached[loadIndex] = true;
                    cacheEndReached[loadIndex] = true;
                }
                if (obj.getId() > 0) {
                    maxMessageId[loadIndex] = Math.min(obj.getId(), maxMessageId[loadIndex]);
                    minMessageId[loadIndex] = Math.max(obj.getId(), minMessageId[loadIndex]);
                } else if (currentEncryptedChat != null) {
                    maxMessageId[loadIndex] = Math.max(obj.getId(), maxMessageId[loadIndex]);
                    minMessageId[loadIndex] = Math.min(obj.getId(), minMessageId[loadIndex]);
                }
                if (obj.messageOwner.date != 0) {
                    maxDate[loadIndex] = Math.max(maxDate[loadIndex], obj.messageOwner.date);
                    if (minDate[loadIndex] == 0 || obj.messageOwner.date < minDate[loadIndex]) {
                        minDate[loadIndex] = obj.messageOwner.date;
                    }
                }

                if (obj.type < 0 || loadIndex == 1
                        && obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                    continue;
                }

                if (!obj.isOut() && obj.isUnread()) {
                    wasUnread = true;
                }
                messagesDict[loadIndex].put(obj.getId(), obj);
                ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);

                if (dayArray == null) {
                    dayArray = new ArrayList<>();
                    messagesByDays.put(obj.dateKey, dayArray);
                    TLRPC.Message dateMsg = new TLRPC.Message();
                    dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
                    dateMsg.id = 0;
                    dateMsg.date = obj.messageOwner.date;
                    MessageObject dateObj = new MessageObject(dateMsg, null, false);
                    dateObj.type = 10;
                    dateObj.contentType = 1;
                    if (load_type == 1) {
                        messages.add(0, dateObj);
                    } else {
                        messages.add(dateObj);
                    }
                    newRowsCount++;
                }

                newRowsCount++;
                if (load_type == 1) {
                    dayArray.add(obj);
                    messages.add(0, obj);
                }

                if (load_type != 1) {
                    dayArray.add(obj);
                    messages.add(messages.size() - 1, obj);
                }

                if (obj.getId() == last_message_id) {
                    forwardEndReached[loadIndex] = true;
                }

                if (load_type == 2 && obj.getId() == first_unread_id) {
                    if (approximateHeightSum > AndroidUtilities.displaySize.y / 2 || !forwardEndReached[0]) {
                        TLRPC.Message dateMsg = new TLRPC.Message();
                        dateMsg.message = "";
                        dateMsg.id = 0;
                        MessageObject dateObj = new MessageObject(dateMsg, null, false);
                        dateObj.type = 6;
                        dateObj.contentType = 2;
                        messages.add(messages.size() - 1, dateObj);
                        unreadMessageObject = dateObj;
                        scrollToMessage = unreadMessageObject;
                        scrollToMessagePosition = -10000;
                        newRowsCount++;
                    }
                } else if (load_type == 3 && obj.getId() == startLoadFromMessageId) {
                    if (needSelectFromMessageId) {
                        highlightMessageId = obj.getId();
                    } else {
                        highlightMessageId = Integer.MAX_VALUE;
                    }
                    scrollToMessage = obj;
                    startLoadFromMessageId = 0;
                    if (scrollToMessagePosition == -10000) {
                        scrollToMessagePosition = -9000;
                    }
                }
            }
            if (load_type == 0 && newRowsCount == 0) {
                loadsCount--;
            }

            if (forwardEndReached[loadIndex] && loadIndex != 1) {
                first_unread_id = 0;
                last_message_id = 0;
            }

            if (loadsCount <= 2) {
                if (!isCache) {
                    updateSpamView();
                }
            }

            if (load_type == 1) {
                if (messArr.size() != count && !isCache) {
                    forwardEndReached[loadIndex] = true;
                    if (loadIndex != 1) {
                        first_unread_id = 0;
                        last_message_id = 0;
                        chatAdapter.notifyItemRemoved(chatAdapter.getItemCount() - 1);
                        newRowsCount--;
                    }
                    startLoadFromMessageId = 0;
                }
                if (newRowsCount > 0) {
                    int firstVisPos = chatLayoutManager.findLastVisibleItemPosition();
                    int top = 0;
                    if (firstVisPos != chatLayoutManager.getItemCount() - 1) {
                        firstVisPos = RecyclerView.NO_POSITION;
                    } else {
                        View firstVisView = chatLayoutManager.findViewByPosition(firstVisPos);
                        top = ((firstVisView == null) ? 0 : firstVisView.getTop())
                                - chatListView.getPaddingTop();
                    }
                    chatAdapter.notifyItemRangeInserted(chatAdapter.getItemCount() - 1, newRowsCount);
                    if (firstVisPos != RecyclerView.NO_POSITION) {
                        chatLayoutManager.scrollToPositionWithOffset(firstVisPos, top);
                    }
                }
                loadingForward = false;
            } else {
                if (messArr.size() < count && load_type != 3) {
                    if (isCache) {
                        if (currentEncryptedChat != null || isBroadcast) {
                            endReached[loadIndex] = true;
                        }
                        if (load_type != 2) {
                            cacheEndReached[loadIndex] = true;
                        }
                    } else if (load_type != 2) {
                        endReached[loadIndex] = true;// =TODO if < 7 from unread
                    }
                }
                loading = false;

                if (chatListView != null) {
                    if (first || scrollToTopOnResume || forceScrollToTop) {
                        forceScrollToTop = false;
                        chatAdapter.notifyDataSetChanged();
                        if (scrollToMessage != null) {
                            int yOffset;
                            if (scrollToMessagePosition == -9000) {
                                yOffset = Math.max(0,
                                        (chatListView.getHeight() - scrollToMessage.getApproximateHeight())
                                                / 2);
                            } else if (scrollToMessagePosition == -10000) {
                                yOffset = 0;
                            } else {
                                yOffset = scrollToMessagePosition;
                            }
                            if (!messages.isEmpty()) {
                                if (messages.get(messages.size() - 1) == scrollToMessage
                                        || messages.get(messages.size() - 2) == scrollToMessage) {
                                    chatLayoutManager.scrollToPositionWithOffset((chatAdapter.isBot ? 1 : 0),
                                            -chatListView.getPaddingTop() - AndroidUtilities.dp(7) + yOffset);
                                } else {
                                    chatLayoutManager.scrollToPositionWithOffset(
                                            chatAdapter.messagesStartRow + messages.size()
                                                    - messages.indexOf(scrollToMessage) - 1,
                                            -chatListView.getPaddingTop() - AndroidUtilities.dp(7) + yOffset);
                                }
                            }
                            chatListView.invalidate();
                            if (scrollToMessagePosition == -10000 || scrollToMessagePosition == -9000) {
                                showPagedownButton(true, true);
                            }
                            scrollToMessagePosition = -10000;
                            scrollToMessage = null;
                        } else {
                            moveScrollToLastMessage();
                        }
                    } else {
                        if (newRowsCount != 0) {
                            boolean end = false;
                            if (endReached[loadIndex]
                                    && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
                                end = true;
                                chatAdapter.notifyItemRangeChanged(chatAdapter.isBot ? 1 : 0, 2);
                            }
                            int firstVisPos = chatLayoutManager.findLastVisibleItemPosition();
                            View firstVisView = chatLayoutManager.findViewByPosition(firstVisPos);
                            int top = ((firstVisView == null) ? 0 : firstVisView.getTop())
                                    - chatListView.getPaddingTop();
                            if (newRowsCount - (end ? 1 : 0) > 0) {
                                chatAdapter.notifyItemRangeInserted((chatAdapter.isBot ? 2 : 1) + (end ? 0 : 1),
                                        newRowsCount - (end ? 1 : 0));
                            }
                            if (firstVisPos != -1) {
                                chatLayoutManager.scrollToPositionWithOffset(
                                        firstVisPos + newRowsCount - (end ? 1 : 0), top);
                            }
                        } else if (endReached[loadIndex]
                                && (loadIndex == 0 && mergeDialogId == 0 || loadIndex == 1)) {
                            chatAdapter.notifyItemRemoved(chatAdapter.isBot ? 1 : 0);
                        }
                    }

                    if (paused) {
                        scrollToTopOnResume = true;
                        if (scrollToMessage != null) {
                            scrollToTopUnReadOnResume = true;
                        }
                    }

                    if (first) {
                        if (chatListView != null) {
                            chatListView.setEmptyView(emptyViewContainer);
                        }
                    }
                } else {
                    scrollToTopOnResume = true;
                    if (scrollToMessage != null) {
                        scrollToTopUnReadOnResume = true;
                    }
                }
            }

            if (first && messages.size() > 0) {
                if (loadIndex == 0) {
                    final boolean wasUnreadFinal = wasUnread;
                    final int last_unread_date_final = last_unread_date;
                    final int lastid = messages.get(0).getId();
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            if (last_message_id != 0) {
                                MessagesController.getInstance().markDialogAsRead(dialog_id, lastid,
                                        last_message_id, last_unread_date_final, wasUnreadFinal, false);
                            } else {
                                MessagesController.getInstance().markDialogAsRead(dialog_id, lastid,
                                        minMessageId[0], maxDate[0], wasUnreadFinal, false);
                            }
                        }
                    }, 700);
                }
                first = false;
            }
            if (messages.isEmpty() && currentEncryptedChat == null && currentUser != null && currentUser.bot
                    && botUser == null) {
                botUser = "";
                updateBottomOverlay();
            }

            if (newRowsCount == 0 && currentEncryptedChat != null && !endReached[0]) {
                first = true;
                if (chatListView != null) {
                    chatListView.setEmptyView(null);
                }
                if (emptyViewContainer != null) {
                    emptyViewContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
            }
            checkScrollForLoad(false);
        }
    } else if (id == NotificationCenter.emojiDidLoaded) {
        if (chatListView != null) {
            chatListView.invalidateViews();
        }
        if (replyObjectTextView != null) {
            replyObjectTextView.invalidate();
        }
        if (alertTextView != null) {
            alertTextView.invalidate();
        }
        if (pinnedMessageTextView != null) {
            pinnedMessageTextView.invalidate();
        }
        if (mentionListView != null) {
            mentionListView.invalidateViews();
        }
    } else if (id == NotificationCenter.updateInterfaces) {
        int updateMask = (Integer) args[0];
        if ((updateMask & MessagesController.UPDATE_MASK_NAME) != 0
                || (updateMask & MessagesController.UPDATE_MASK_CHAT_NAME) != 0) {
            if (currentChat != null) {
                TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id);
                if (chat != null) {
                    currentChat = chat;
                }
            } else if (currentUser != null) {
                TLRPC.User user = MessagesController.getInstance().getUser(currentUser.id);
                if (user != null) {
                    currentUser = user;
                }
            }
            updateTitle();
        }
        boolean updateSubtitle = false;
        if ((updateMask & MessagesController.UPDATE_MASK_CHAT_MEMBERS) != 0
                || (updateMask & MessagesController.UPDATE_MASK_STATUS) != 0) {
            if (currentChat != null && avatarContainer != null) {
                avatarContainer.updateOnlineCount();
            }
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_AVATAR) != 0
                || (updateMask & MessagesController.UPDATE_MASK_CHAT_AVATAR) != 0
                || (updateMask & MessagesController.UPDATE_MASK_NAME) != 0) {
            checkAndUpdateAvatar();
            updateVisibleRows();
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PRINT) != 0) {
            updateSubtitle = true;
        }
        if ((updateMask & MessagesController.UPDATE_MASK_CHANNEL) != 0 && ChatObject.isChannel(currentChat)) {
            TLRPC.Chat chat = MessagesController.getInstance().getChat(currentChat.id);
            if (chat == null) {
                return;
            }
            currentChat = chat;
            updateSubtitle = true;
            updateBottomOverlay();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setDialogId(dialog_id);
            }
        }
        if (avatarContainer != null && updateSubtitle) {
            avatarContainer.updateSubtitle();
        }
        if ((updateMask & MessagesController.UPDATE_MASK_USER_PHONE) != 0) {
            updateContactStatus();
        }
    } else if (id == NotificationCenter.didReceivedNewMessages) {

        //   (  ?  ?
        Log.d(LOG_TAG, "didReceivedNewMessage : " + id);
        long did = (Long) args[0];
        if (did == dialog_id) {

            boolean updateChat = false;
            boolean hasFromMe = false;
            ArrayList<MessageObject> arr = (ArrayList<MessageObject>) args[1];
            if (currentEncryptedChat != null && arr.size() == 1) {
                MessageObject obj = arr.get(0);

                if (currentEncryptedChat != null && obj.isOut() && obj.messageOwner.action != null
                        && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                        && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL
                        && getParentActivity() != null) {
                    if (AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) < 17
                            && currentEncryptedChat.ttl > 0 && currentEncryptedChat.ttl <= 60) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(
                                LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                        builder.setPositiveButton(
                                LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
                        builder.setMessage(LocaleController.formatString("CompatibilityChat",
                                kr.wdream.storyshop.R.string.CompatibilityChat, currentUser.first_name,
                                currentUser.first_name));
                        showDialog(builder.create());
                    }
                }
            }
            if (currentChat != null || inlineReturn != 0) {
                for (int a = 0; a < arr.size(); a++) {
                    MessageObject messageObject = arr.get(a);
                    if (currentChat != null) {
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser
                                && messageObject.messageOwner.action.user_id == UserConfig.getClientUserId()
                                || messageObject.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                        && messageObject.messageOwner.action.users
                                                .contains(UserConfig.getClientUserId())) {
                            TLRPC.Chat newChat = MessagesController.getInstance().getChat(currentChat.id);
                            if (newChat != null) {
                                currentChat = newChat;
                                checkActionBarMenu();
                                updateBottomOverlay();
                                if (avatarContainer != null) {
                                    avatarContainer.updateSubtitle();
                                }
                            }
                        } else if (messageObject.messageOwner.reply_to_msg_id != 0
                                && messageObject.replyMessageObject == null) {
                            messageObject.replyMessageObject = messagesDict[0]
                                    .get(messageObject.messageOwner.reply_to_msg_id);
                            if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionPinMessage) {
                                messageObject.generatePinMessageText(null, null);
                            } else if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                                messageObject.generateGameMessageText(null);
                            }
                        }
                    } else if (inlineReturn != 0) {
                        if (messageObject.messageOwner.reply_markup != null) {
                            for (int b = 0; b < messageObject.messageOwner.reply_markup.rows.size(); b++) {
                                TLRPC.TL_keyboardButtonRow row = messageObject.messageOwner.reply_markup.rows
                                        .get(b);
                                for (int c = 0; c < row.buttons.size(); c++) {
                                    TLRPC.KeyboardButton button = row.buttons.get(c);
                                    if (button instanceof TLRPC.TL_keyboardButtonSwitchInline) {
                                        processSwitchButton((TLRPC.TL_keyboardButtonSwitchInline) button);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            boolean reloadMegagroup = false;
            if (!forwardEndReached[0]) {
                int currentMaxDate = Integer.MIN_VALUE;
                int currentMinMsgId = Integer.MIN_VALUE;
                if (currentEncryptedChat != null) {
                    currentMinMsgId = Integer.MAX_VALUE;
                }
                boolean currentMarkAsRead = false;

                for (int a = 0; a < arr.size(); a++) {
                    MessageObject obj = arr.get(a);
                    if (currentUser != null && currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                    if (avatarContainer != null && currentEncryptedChat != null
                            && obj.messageOwner.action != null
                            && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                            && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
                        avatarContainer.setTime(
                                ((TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction).ttl_seconds);
                    }
                    if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        final Bundle bundle = new Bundle();
                        bundle.putInt("chat_id", obj.messageOwner.action.channel_id);
                        final BaseFragment lastFragment = parentLayout.fragmentsStack.size() > 0
                                ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1)
                                : null;
                        final int channel_id = obj.messageOwner.action.channel_id;
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                ActionBarLayout parentLayout = ChatActivity.this.parentLayout;
                                if (lastFragment != null) {
                                    NotificationCenter.getInstance().removeObserver(lastFragment,
                                            NotificationCenter.closeChats);
                                }
                                NotificationCenter.getInstance()
                                        .postNotificationName(NotificationCenter.closeChats);
                                parentLayout.presentFragment(new ChatActivity(bundle), true);
                                AndroidUtilities.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessagesController.getInstance().loadFullChat(channel_id, 0, true);
                                    }
                                }, 1000);
                            }
                        });
                        return;
                    } else if (currentChat != null && currentChat.megagroup
                            && (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                    || obj.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser)) {
                        reloadMegagroup = true;
                    }
                    if (obj.isOut() && obj.isSending()) {
                        scrollToLastMessage(false);
                        return;
                    }
                    if (obj.type < 0 || messagesDict[0].containsKey(obj.getId())) {
                        continue;
                    }
                    obj.checkLayout();
                    currentMaxDate = Math.max(currentMaxDate, obj.messageOwner.date);
                    if (obj.getId() > 0) {
                        currentMinMsgId = Math.max(obj.getId(), currentMinMsgId);
                        last_message_id = Math.max(last_message_id, obj.getId());
                    } else if (currentEncryptedChat != null) {
                        currentMinMsgId = Math.min(obj.getId(), currentMinMsgId);
                        last_message_id = Math.min(last_message_id, obj.getId());
                    }

                    if (!obj.isOut() && obj.isUnread()) {
                        unread_to_load++;
                        currentMarkAsRead = true;
                    }
                    if (obj.type == 10 || obj.type == 11) {
                        updateChat = true;
                    }
                }

                if (currentMarkAsRead) {
                    if (paused) {
                        readWhenResume = true;
                        readWithDate = currentMaxDate;
                        readWithMid = currentMinMsgId;
                    } else {
                        if (messages.size() > 0) {
                            MessagesController.getInstance().markDialogAsRead(dialog_id,
                                    messages.get(0).getId(), currentMinMsgId, currentMaxDate, true, false);
                        }
                    }
                }
                updateVisibleRows();
            } else {
                boolean markAsRead = false;
                boolean unreadUpdated = true;
                int oldCount = messages.size();
                int addedCount = 0;
                HashMap<String, ArrayList<MessageObject>> webpagesToReload = null;
                int placeToPaste = -1;
                for (int a = 0; a < arr.size(); a++) {
                    MessageObject obj = arr.get(a);
                    if (a == 0) {
                        if (obj.messageOwner.id < 0) {
                            placeToPaste = 0;
                        } else {
                            if (!messages.isEmpty()) {
                                int size = messages.size();
                                for (int b = 0; b < size; b++) {
                                    MessageObject lastMessage = messages.get(b);
                                    if (lastMessage.type >= 0 && lastMessage.messageOwner.date > 0) {
                                        if (lastMessage.messageOwner.id > 0 && obj.messageOwner.id > 0) {
                                            if (lastMessage.messageOwner.id < obj.messageOwner.id) {
                                                placeToPaste = b;
                                                break;
                                            }
                                        } else {
                                            if (lastMessage.messageOwner.date < obj.messageOwner.date) {
                                                placeToPaste = b;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (placeToPaste == -1 || placeToPaste > messages.size()) {
                                    placeToPaste = messages.size();
                                }
                            } else {
                                placeToPaste = 0;
                            }
                        }
                    }
                    if (currentUser != null && currentUser.bot && obj.isOut()) {
                        obj.setIsRead();
                    }
                    if (avatarContainer != null && currentEncryptedChat != null
                            && obj.messageOwner.action != null
                            && obj.messageOwner.action instanceof TLRPC.TL_messageEncryptedAction
                            && obj.messageOwner.action.encryptedAction instanceof TLRPC.TL_decryptedMessageActionSetMessageTTL) {
                        avatarContainer.setTime(
                                ((TLRPC.TL_decryptedMessageActionSetMessageTTL) obj.messageOwner.action.encryptedAction).ttl_seconds);
                    }
                    if (obj.type < 0 || messagesDict[0].containsKey(obj.getId())) {
                        continue;
                    }
                    if (currentEncryptedChat != null
                            && obj.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage
                            && obj.messageOwner.media.webpage instanceof TLRPC.TL_webPageUrlPending) {
                        if (webpagesToReload == null) {
                            webpagesToReload = new HashMap<>();
                        }
                        ArrayList<MessageObject> arrayList = webpagesToReload
                                .get(obj.messageOwner.media.webpage.url);
                        if (arrayList == null) {
                            arrayList = new ArrayList<>();
                            webpagesToReload.put(obj.messageOwner.media.webpage.url, arrayList);
                        }
                        arrayList.add(obj);
                    }
                    obj.checkLayout();
                    if (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatMigrateTo) {
                        final Bundle bundle = new Bundle();
                        bundle.putInt("chat_id", obj.messageOwner.action.channel_id);
                        final BaseFragment lastFragment = parentLayout.fragmentsStack.size() > 0
                                ? parentLayout.fragmentsStack.get(parentLayout.fragmentsStack.size() - 1)
                                : null;
                        final int channel_id = obj.messageOwner.action.channel_id;
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                ActionBarLayout parentLayout = ChatActivity.this.parentLayout;
                                if (lastFragment != null) {
                                    NotificationCenter.getInstance().removeObserver(lastFragment,
                                            NotificationCenter.closeChats);
                                }
                                NotificationCenter.getInstance()
                                        .postNotificationName(NotificationCenter.closeChats);
                                parentLayout.presentFragment(new ChatActivity(bundle), true);
                                AndroidUtilities.runOnUIThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MessagesController.getInstance().loadFullChat(channel_id, 0, true);
                                    }
                                }, 1000);
                            }
                        });
                        return;
                    } else if (currentChat != null && currentChat.megagroup
                            && (obj.messageOwner.action instanceof TLRPC.TL_messageActionChatAddUser
                                    || obj.messageOwner.action instanceof TLRPC.TL_messageActionChatDeleteUser)) {
                        reloadMegagroup = true;
                    }
                    if (minDate[0] == 0 || obj.messageOwner.date < minDate[0]) {
                        minDate[0] = obj.messageOwner.date;
                    }

                    if (obj.isOut()) {
                        removeUnreadPlane();
                        hasFromMe = true;
                    }

                    if (obj.getId() > 0) {
                        maxMessageId[0] = Math.min(obj.getId(), maxMessageId[0]);
                        minMessageId[0] = Math.max(obj.getId(), minMessageId[0]);
                    } else if (currentEncryptedChat != null) {
                        maxMessageId[0] = Math.max(obj.getId(), maxMessageId[0]);
                        minMessageId[0] = Math.min(obj.getId(), minMessageId[0]);
                    }
                    maxDate[0] = Math.max(maxDate[0], obj.messageOwner.date);
                    messagesDict[0].put(obj.getId(), obj);
                    ArrayList<MessageObject> dayArray = messagesByDays.get(obj.dateKey);
                    if (dayArray == null) {
                        dayArray = new ArrayList<>();
                        messagesByDays.put(obj.dateKey, dayArray);
                        TLRPC.Message dateMsg = new TLRPC.Message();
                        dateMsg.message = LocaleController.formatDateChat(obj.messageOwner.date);
                        dateMsg.id = 0;
                        dateMsg.date = obj.messageOwner.date;
                        MessageObject dateObj = new MessageObject(dateMsg, null, false);
                        dateObj.type = 10;
                        dateObj.contentType = 1;
                        messages.add(placeToPaste, dateObj);
                        addedCount++;
                    }
                    if (!obj.isOut()) {
                        if (paused && placeToPaste == 0) {
                            if (!scrollToTopUnReadOnResume && unreadMessageObject != null) {
                                removeMessageObject(unreadMessageObject);
                                if (placeToPaste > 0) {
                                    placeToPaste--;
                                }
                                unreadMessageObject = null;
                            }
                            if (unreadMessageObject == null) {
                                TLRPC.Message dateMsg = new TLRPC.Message();
                                dateMsg.message = "";
                                dateMsg.id = 0;
                                MessageObject dateObj = new MessageObject(dateMsg, null, false);
                                dateObj.type = 6;
                                dateObj.contentType = 2;
                                messages.add(0, dateObj);
                                unreadMessageObject = dateObj;
                                scrollToMessage = unreadMessageObject;
                                scrollToMessagePosition = -10000;
                                unreadUpdated = false;
                                unread_to_load = 0;
                                scrollToTopUnReadOnResume = true;
                                addedCount++;
                            }
                        }
                        if (unreadMessageObject != null) {
                            unread_to_load++;
                            unreadUpdated = true;
                        }
                        if (obj.isUnread()) {
                            if (!paused) {
                                obj.setIsRead();
                            }
                            markAsRead = true;
                        }
                    }

                    dayArray.add(0, obj);
                    if (placeToPaste > messages.size()) {
                        placeToPaste = messages.size();
                    }
                    messages.add(placeToPaste, obj);
                    addedCount++;
                    newUnreadMessageCount++;
                    if (obj.type == 10 || obj.type == 11) {
                        updateChat = true;
                    }
                }
                if (webpagesToReload != null) {
                    MessagesController.getInstance().reloadWebPages(dialog_id, webpagesToReload);
                }

                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
                if (chatAdapter != null) {
                    if (unreadUpdated) {
                        chatAdapter.updateRowWithMessageObject(unreadMessageObject);
                    }
                    if (addedCount != 0) {
                        chatAdapter.notifyItemRangeInserted(chatAdapter.getItemCount() - placeToPaste,
                                addedCount);
                    }
                } else {
                    scrollToTopOnResume = true;
                }

                if (chatListView != null && chatAdapter != null) {
                    int lastVisible = chatLayoutManager.findLastVisibleItemPosition();
                    if (lastVisible == RecyclerView.NO_POSITION) {
                        lastVisible = 0;
                    }
                    if (endReached[0]) {
                        lastVisible++;
                    }
                    if (chatAdapter.isBot) {
                        oldCount++;
                    }
                    if (lastVisible >= oldCount || hasFromMe) {
                        newUnreadMessageCount = 0;
                        if (!firstLoading) {
                            if (paused) {
                                scrollToTopOnResume = true;
                            } else {
                                forceScrollToTop = true;
                                moveScrollToLastMessage();
                            }
                        }
                    } else {
                        if (newUnreadMessageCount != 0 && pagedownButtonCounter != null) {
                            pagedownButtonCounter.setVisibility(View.VISIBLE);
                            pagedownButtonCounter.setText(String.format("%d", newUnreadMessageCount));
                        }
                        showPagedownButton(true, true);
                    }
                } else {
                    scrollToTopOnResume = true;
                }

                if (markAsRead) {
                    if (paused) {
                        readWhenResume = true;
                        readWithDate = maxDate[0];
                        readWithMid = minMessageId[0];
                    } else {
                        MessagesController.getInstance().markDialogAsRead(dialog_id, messages.get(0).getId(),
                                minMessageId[0], maxDate[0], true, false);
                    }
                }
            }
            if (!messages.isEmpty() && botUser != null && botUser.length() == 0) {
                botUser = null;
                updateBottomOverlay();
            }
            if (updateChat) {
                updateTitle();
                checkAndUpdateAvatar();
            }
            if (reloadMegagroup) {
                MessagesController.getInstance().loadFullChat(currentChat.id, 0, true);
            }
        }
    } else if (id == NotificationCenter.closeChats) {
        if (args != null && args.length > 0) {
            long did = (Long) args[0];
            if (did == dialog_id) {
                finishFragment();
            }
        } else {
            removeSelfFromStack();
        }
    } else if (id == NotificationCenter.messagesRead) {
        SparseArray<Long> inbox = (SparseArray<Long>) args[0];
        SparseArray<Long> outbox = (SparseArray<Long>) args[1];
        boolean updated = false;
        for (int b = 0; b < inbox.size(); b++) {
            int key = inbox.keyAt(b);
            long messageId = inbox.get(key);
            if (key != dialog_id) {
                continue;
            }
            for (int a = 0; a < messages.size(); a++) {
                MessageObject obj = messages.get(a);
                if (!obj.isOut() && obj.getId() > 0 && obj.getId() <= (int) messageId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    updated = true;
                }
            }
            break;
        }
        for (int b = 0; b < outbox.size(); b++) {
            int key = outbox.keyAt(b);
            int messageId = (int) ((long) outbox.get(key));
            if (key != dialog_id) {
                continue;
            }
            for (int a = 0; a < messages.size(); a++) {
                MessageObject obj = messages.get(a);
                if (obj.isOut() && obj.getId() > 0 && obj.getId() <= messageId) {
                    if (!obj.isUnread()) {
                        break;
                    }
                    obj.setIsRead();
                    updated = true;
                }
            }
            break;
        }
        if (updated) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.messagesDeleted) {
        ArrayList<Integer> markAsDeletedMessages = (ArrayList<Integer>) args[0];
        int channelId = (Integer) args[1];
        int loadIndex = 0;
        if (ChatObject.isChannel(currentChat)) {
            if (channelId == 0 && mergeDialogId != 0) {
                loadIndex = 1;
            } else if (channelId == currentChat.id) {
                loadIndex = 0;
            } else {
                return;
            }
        } else if (channelId != 0) {
            return;
        }
        boolean updated = false;
        for (int a = 0; a < markAsDeletedMessages.size(); a++) {
            Integer ids = markAsDeletedMessages.get(a);
            MessageObject obj = messagesDict[loadIndex].get(ids);
            if (loadIndex == 0 && info != null && info.pinned_msg_id == ids) {
                pinnedMessageObject = null;
                info.pinned_msg_id = 0;
                MessagesStorage.getInstance().updateChannelPinnedMessage(channelId, 0);
                updatePinnedMessageView(true);
            }
            if (obj != null) {
                int index = messages.indexOf(obj);
                if (index != -1) {
                    messages.remove(index);
                    messagesDict[loadIndex].remove(ids);
                    ArrayList<MessageObject> dayArr = messagesByDays.get(obj.dateKey);
                    if (dayArr != null) {
                        dayArr.remove(obj);
                        if (dayArr.isEmpty()) {
                            messagesByDays.remove(obj.dateKey);
                            if (index >= 0 && index < messages.size()) {
                                messages.remove(index);
                            }
                        }
                    }
                    updated = true;
                }
            }
        }
        if (messages.isEmpty()) {
            if (!endReached[0] && !loading) {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                }
                if (chatListView != null) {
                    chatListView.setEmptyView(null);
                }
                if (currentEncryptedChat == null) {
                    maxMessageId[0] = maxMessageId[1] = Integer.MAX_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MIN_VALUE;
                } else {
                    maxMessageId[0] = maxMessageId[1] = Integer.MIN_VALUE;
                    minMessageId[0] = minMessageId[1] = Integer.MAX_VALUE;
                }
                maxDate[0] = maxDate[1] = Integer.MIN_VALUE;
                minDate[0] = minDate[1] = 0;
                waitingForLoad.add(lastLoadIndex);
                MessagesController.getInstance().loadMessages(dialog_id, 30, 0, !cacheEndReached[0], minDate[0],
                        classGuid, 0, 0, ChatObject.isChannel(currentChat), lastLoadIndex++);
                loading = true;
            } else {
                if (botButtons != null) {
                    botButtons = null;
                    if (chatActivityEnterView != null) {
                        chatActivityEnterView.setButtons(null, false);
                    }
                }
                if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
                    botUser = "";
                    updateBottomOverlay();
                }
            }
        }
        if (updated && chatAdapter != null) {
            removeUnreadPlane();
            chatAdapter.notifyDataSetChanged();
        }
    } else if (id == NotificationCenter.messageReceivedByServer) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            Integer newMsgId = (Integer) args[1];
            if (!newMsgId.equals(msgId) && messagesDict[0].containsKey(newMsgId)) {
                MessageObject removed = messagesDict[0].remove(msgId);
                if (removed != null) {
                    int index = messages.indexOf(removed);
                    messages.remove(index);
                    ArrayList<MessageObject> dayArr = messagesByDays.get(removed.dateKey);
                    dayArr.remove(obj);
                    if (dayArr.isEmpty()) {
                        messagesByDays.remove(obj.dateKey);
                        if (index >= 0 && index < messages.size()) {
                            messages.remove(index);
                        }
                    }
                    if (chatAdapter != null) {
                        chatAdapter.notifyDataSetChanged();
                    }
                }
                return;
            }
            TLRPC.Message newMsgObj = (TLRPC.Message) args[2];
            boolean mediaUpdated = false;
            boolean updatedForward = false;
            if (newMsgObj != null) {
                try {
                    updatedForward = obj.isForwarded()
                            && (obj.messageOwner.reply_markup == null && newMsgObj.reply_markup != null
                                    || !obj.messageOwner.message.equals(newMsgObj.message));
                    mediaUpdated = updatedForward
                            || obj.messageOwner.params != null
                                    && obj.messageOwner.params.containsKey("query_id")
                            || newMsgObj.media != null && obj.messageOwner.media != null
                                    && !newMsgObj.media.getClass().equals(obj.messageOwner.media.getClass());
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                obj.messageOwner = newMsgObj;
                obj.generateThumbs(true);
                obj.setType();
                if (newMsgObj.media instanceof TLRPC.TL_messageMediaGame) {
                    obj.applyNewText();
                }
            }
            if (updatedForward) {
                obj.measureInlineBotButtons();
            }
            messagesDict[0].remove(msgId);
            messagesDict[0].put(newMsgId, obj);
            obj.messageOwner.id = newMsgId;
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            obj.forceUpdate = mediaUpdated;
            ArrayList<MessageObject> messArr = new ArrayList<>();
            messArr.add(obj);
            if (currentEncryptedChat == null) {
                MessagesQuery.loadReplyMessagesForMessages(messArr, dialog_id);
            }
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj);
            }
            if (chatLayoutManager != null) {
                if (mediaUpdated && chatLayoutManager.findLastVisibleItemPosition() >= messages.size() - 1) {
                    moveScrollToLastMessage();
                }
            }
            NotificationsController.getInstance().playOutChatSound();
        }
    } else if (id == NotificationCenter.messageReceivedByAck) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SENT;
            if (chatAdapter != null) {
                chatAdapter.updateRowWithMessageObject(obj);
            }
        }
    } else if (id == NotificationCenter.messageSendError) {
        Integer msgId = (Integer) args[0];
        MessageObject obj = messagesDict[0].get(msgId);
        if (obj != null) {
            obj.messageOwner.send_state = MessageObject.MESSAGE_SEND_STATE_SEND_ERROR;
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.chatInfoDidLoaded) {
        TLRPC.ChatFull chatFull = (TLRPC.ChatFull) args[0];
        if (currentChat != null && chatFull.id == currentChat.id) {
            if (chatFull instanceof TLRPC.TL_channelFull) {
                if (currentChat.megagroup) {
                    int lastDate = 0;
                    if (chatFull.participants != null) {
                        for (int a = 0; a < chatFull.participants.participants.size(); a++) {
                            lastDate = Math.max(chatFull.participants.participants.get(a).date, lastDate);
                        }
                    }
                    if (lastDate == 0 || Math.abs(System.currentTimeMillis() / 1000 - lastDate) > 60 * 60) {
                        MessagesController.getInstance().loadChannelParticipants(currentChat.id);
                    }
                }
                if (chatFull.participants == null && info != null) {
                    chatFull.participants = info.participants;
                }
            }
            info = chatFull;
            if (mentionsAdapter != null) {
                mentionsAdapter.setChatInfo(info);
            }
            if (args[3] instanceof MessageObject) {
                pinnedMessageObject = (MessageObject) args[3];
                updatePinnedMessageView(false);
            } else {
                updatePinnedMessageView(true);
            }
            if (avatarContainer != null) {
                avatarContainer.updateOnlineCount();
                avatarContainer.updateSubtitle();
            }
            if (isBroadcast) {
                SendMessagesHelper.getInstance().setCurrentChatInfo(info);
            }
            if (info instanceof TLRPC.TL_chatFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = false;
                for (int a = 0; a < info.participants.participants.size(); a++) {
                    TLRPC.ChatParticipant participant = info.participants.participants.get(a);
                    TLRPC.User user = MessagesController.getInstance().getUser(participant.user_id);
                    if (user != null && user.bot) {
                        URLSpanBotCommand.enabled = true;
                        botsCount++;
                        BotQuery.loadBotInfo(user.id, true, classGuid);
                    }
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
            } else if (info instanceof TLRPC.TL_channelFull) {
                hasBotsCommands = false;
                botInfo.clear();
                botsCount = 0;
                URLSpanBotCommand.enabled = !info.bot_info.isEmpty();
                botsCount = info.bot_info.size();
                for (int a = 0; a < info.bot_info.size(); a++) {
                    TLRPC.BotInfo bot = info.bot_info.get(a);
                    if (!bot.commands.isEmpty() && (!ChatObject.isChannel(currentChat)
                            || currentChat != null && currentChat.megagroup)) {
                        hasBotsCommands = true;
                    }
                    botInfo.put(bot.user_id, bot);
                }
                if (chatListView != null) {
                    chatListView.invalidateViews();
                }
                if (mentionsAdapter != null && (!ChatObject.isChannel(currentChat)
                        || currentChat != null && currentChat.megagroup)) {
                    mentionsAdapter.setBotInfo(botInfo);
                }
            }
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setBotsCount(botsCount);
            }
            if (ChatObject.isChannel(currentChat) && mergeDialogId == 0 && info.migrated_from_chat_id != 0) {
                mergeDialogId = -info.migrated_from_chat_id;
                maxMessageId[1] = info.migrated_from_max_id;
                if (chatAdapter != null) {
                    chatAdapter.notifyDataSetChanged();
                }
            }
        }
    } else if (id == NotificationCenter.chatInfoCantLoad) {
        int chatId = (Integer) args[0];
        if (currentChat != null && currentChat.id == chatId) {
            int reason = (Integer) args[1];
            if (getParentActivity() == null || closeChatDialog != null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
            if (reason == 0) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenPrivate",
                        kr.wdream.storyshop.R.string.ChannelCantOpenPrivate));
            } else if (reason == 1) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenNa",
                        kr.wdream.storyshop.R.string.ChannelCantOpenNa));
            } else if (reason == 2) {
                builder.setMessage(LocaleController.getString("ChannelCantOpenBanned",
                        kr.wdream.storyshop.R.string.ChannelCantOpenBanned));
            }
            builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK), null);
            showDialog(closeChatDialog = builder.create());

            loading = false;
            if (progressView != null) {
                progressView.setVisibility(View.INVISIBLE);
            }
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.contactsDidLoaded) {
        updateContactStatus();
        if (avatarContainer != null) {
            avatarContainer.updateSubtitle();
        }
    } else if (id == NotificationCenter.encryptedChatUpdated) {
        TLRPC.EncryptedChat chat = (TLRPC.EncryptedChat) args[0];
        if (currentEncryptedChat != null && chat.id == currentEncryptedChat.id) {
            currentEncryptedChat = chat;
            updateContactStatus();
            updateSecretStatus();
            initStickers();
            if (chatActivityEnterView != null) {
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.setNeedBotContext(
                        !chatActivityEnterView.isEditingMessage() && (currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46));
            }
        }
    } else if (id == NotificationCenter.messagesReadEncrypted) {
        int encId = (Integer) args[0];
        if (currentEncryptedChat != null && currentEncryptedChat.id == encId) {
            int date = (Integer) args[1];
            for (MessageObject obj : messages) {
                if (!obj.isOut()) {
                    continue;
                } else if (obj.isOut() && !obj.isUnread()) {
                    break;
                }
                if (obj.messageOwner.date - 1 <= date) {
                    obj.setIsRead();
                }
            }
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.audioDidReset || id == NotificationCenter.audioPlayStateChanged) {
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
            count = mentionListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = mentionListView.getChildAt(a);
                if (view instanceof ContextLinkCell) {
                    ContextLinkCell cell = (ContextLinkCell) view;
                    MessageObject messageObject = cell.getMessageObject();
                    if (messageObject != null && (messageObject.isVoice() || messageObject.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.audioProgressDidChanged) {
        Integer mid = (Integer) args[0];
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    if (cell.getMessageObject() != null && cell.getMessageObject().getId() == mid) {
                        MessageObject playing = cell.getMessageObject();
                        MessageObject player = MediaController.getInstance().getPlayingMessageObject();
                        if (player != null) {
                            playing.audioProgress = player.audioProgress;
                            playing.audioProgressSec = player.audioProgressSec;
                            cell.updateAudioProgress();
                        }
                        break;
                    }
                }
            }
        }
    } else if (id == NotificationCenter.removeAllMessagesFromDialog) {
        long did = (Long) args[0];
        if (dialog_id == did) {
            messages.clear();
            waitingForLoad.clear();
            messagesByDays.clear();
            for (int a = 1; a >= 0; a--) {
                messagesDict[a].clear();
                if (currentEncryptedChat == null) {
                    maxMessageId[a] = Integer.MAX_VALUE;
                    minMessageId[a] = Integer.MIN_VALUE;
                } else {
                    maxMessageId[a] = Integer.MIN_VALUE;
                    minMessageId[a] = Integer.MAX_VALUE;
                }
                maxDate[a] = Integer.MIN_VALUE;
                minDate[a] = 0;
                selectedMessagesIds[a].clear();
                selectedMessagesCanCopyIds[a].clear();
            }
            cantDeleteMessagesCount = 0;
            actionBar.hideActionMode();
            updatePinnedMessageView(true);

            if (botButtons != null) {
                botButtons = null;
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.setButtons(null, false);
                }
            }
            if (currentEncryptedChat == null && currentUser != null && currentUser.bot && botUser == null) {
                botUser = "";
                updateBottomOverlay();
            }
            if ((Boolean) args[1]) {
                if (chatAdapter != null) {
                    progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
                    chatListView.setEmptyView(null);
                }
                for (int a = 0; a < 2; a++) {
                    endReached[a] = false;
                    cacheEndReached[a] = false;
                    forwardEndReached[a] = true;
                }
                first = true;
                firstLoading = true;
                loading = true;
                startLoadFromMessageId = 0;
                needSelectFromMessageId = false;
                waitingForLoad.add(lastLoadIndex);
                MessagesController.getInstance().loadMessages(dialog_id, AndroidUtilities.isTablet() ? 30 : 20,
                        0, true, 0, classGuid, 2, 0, ChatObject.isChannel(currentChat), lastLoadIndex++);
            } else {
                if (progressView != null) {
                    progressView.setVisibility(View.INVISIBLE);
                    chatListView.setEmptyView(emptyViewContainer);
                }
            }

            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
            }
        }
    } else if (id == NotificationCenter.screenshotTook) {
        updateInformationForScreenshotDetector();
    } else if (id == NotificationCenter.blockedUsersDidLoaded) {
        if (currentUser != null) {
            boolean oldValue = userBlocked;
            userBlocked = MessagesController.getInstance().blockedUsers.contains(currentUser.id);
            if (oldValue != userBlocked) {
                updateBottomOverlay();
            }
        }
    } else if (id == NotificationCenter.FileNewChunkAvailable) {
        MessageObject messageObject = (MessageObject) args[0];
        long finalSize = (Long) args[2];
        if (finalSize != 0 && dialog_id == messageObject.getDialogId()) {
            MessageObject currentObject = messagesDict[0].get(messageObject.getId());
            if (currentObject != null) {
                currentObject.messageOwner.media.document.size = (int) finalSize;
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.didCreatedNewDeleteTask) {
        SparseArray<ArrayList<Integer>> mids = (SparseArray<ArrayList<Integer>>) args[0];
        boolean changed = false;
        for (int i = 0; i < mids.size(); i++) {
            int key = mids.keyAt(i);
            ArrayList<Integer> arr = mids.get(key);
            for (Integer mid : arr) {
                MessageObject messageObject = messagesDict[0].get(mid);
                if (messageObject != null) {
                    messageObject.messageOwner.destroyTime = key;
                    changed = true;
                }
            }
        }
        if (changed) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.audioDidStarted) {
        MessageObject messageObject = (MessageObject) args[0];
        sendSecretMessageRead(messageObject);
        if (chatListView != null) {
            int count = chatListView.getChildCount();
            for (int a = 0; a < count; a++) {
                View view = chatListView.getChildAt(a);
                if (view instanceof ChatMessageCell) {
                    ChatMessageCell cell = (ChatMessageCell) view;
                    MessageObject messageObject1 = cell.getMessageObject();
                    if (messageObject1 != null && (messageObject1.isVoice() || messageObject1.isMusic())) {
                        cell.updateButtonState(false);
                    }
                }
            }
        }
    } else if (id == NotificationCenter.updateMessageMedia) {
        MessageObject messageObject = (MessageObject) args[0];
        MessageObject existMessageObject = messagesDict[0].get(messageObject.getId());
        if (existMessageObject != null) {
            existMessageObject.messageOwner.media = messageObject.messageOwner.media;
            existMessageObject.messageOwner.attachPath = messageObject.messageOwner.attachPath;
            existMessageObject.generateThumbs(false);
        }
        updateVisibleRows();
    } else if (id == NotificationCenter.replaceMessagesObjects) {
        long did = (long) args[0];
        if (did != dialog_id && did != mergeDialogId) {
            return;
        }
        int loadIndex = did == dialog_id ? 0 : 1;
        boolean changed = false;
        boolean mediaUpdated = false;
        ArrayList<MessageObject> messageObjects = (ArrayList<MessageObject>) args[1];
        for (int a = 0; a < messageObjects.size(); a++) {
            MessageObject messageObject = messageObjects.get(a);
            MessageObject old = messagesDict[loadIndex].get(messageObject.getId());
            if (pinnedMessageObject != null && pinnedMessageObject.getId() == messageObject.getId()) {
                pinnedMessageObject = messageObject;
                updatePinnedMessageView(true);
            }
            if (old != null) {
                if (messageObject.type >= 0) {
                    if (!mediaUpdated
                            && messageObject.messageOwner.media instanceof TLRPC.TL_messageMediaWebPage) {
                        mediaUpdated = true;
                    }
                    if (old.replyMessageObject != null) {
                        messageObject.replyMessageObject = old.replyMessageObject;
                        if (messageObject.messageOwner.action instanceof TLRPC.TL_messageActionGameScore) {
                            messageObject.generateGameMessageText(null);
                        }
                    }
                    messageObject.messageOwner.attachPath = old.messageOwner.attachPath;
                    messageObject.attachPathExists = old.attachPathExists;
                    messageObject.mediaExists = old.mediaExists;
                    messagesDict[loadIndex].put(old.getId(), messageObject);
                } else {
                    messagesDict[loadIndex].remove(old.getId());
                }
                int index = messages.indexOf(old);
                if (index >= 0) {
                    ArrayList<MessageObject> dayArr = messagesByDays.get(old.dateKey);
                    int index2 = -1;
                    if (dayArr != null) {
                        index2 = dayArr.indexOf(old);
                    }
                    if (messageObject.type >= 0) {
                        messages.set(index, messageObject);
                        if (chatAdapter != null) {
                            chatAdapter.notifyItemChanged(
                                    chatAdapter.messagesStartRow + messages.size() - index - 1);
                        }
                        if (index2 >= 0) {
                            dayArr.set(index2, messageObject);
                        }
                    } else {
                        messages.remove(index);
                        if (chatAdapter != null) {
                            chatAdapter.notifyItemRemoved(
                                    chatAdapter.messagesStartRow + messages.size() - index - 1);
                        }
                        if (index2 >= 0) {
                            dayArr.remove(index2);
                            if (dayArr.isEmpty()) {
                                messagesByDays.remove(old.dateKey);
                                messages.remove(index);
                                chatAdapter.notifyItemRemoved(chatAdapter.messagesStartRow + messages.size());
                            }
                        }
                    }
                    changed = true;
                }
            }
        }
        if (changed && chatLayoutManager != null) {
            if (mediaUpdated && chatLayoutManager.findLastVisibleItemPosition() >= messages.size()
                    - (chatAdapter.isBot ? 2 : 1)) {
                moveScrollToLastMessage();
            }
        }
    } else if (id == NotificationCenter.notificationsSettingsUpdated) {
        updateTitleIcons();
        if (ChatObject.isChannel(currentChat)) {
            updateBottomOverlay();
        }
    } else if (id == NotificationCenter.didLoadedReplyMessages) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.didLoadedPinnedMessage) {
        MessageObject message = (MessageObject) args[0];
        if (message.getDialogId() == dialog_id && info != null && info.pinned_msg_id == message.getId()) {
            pinnedMessageObject = message;
            loadingPinnedMessage = 0;
            updatePinnedMessageView(true);
        }
    } else if (id == NotificationCenter.didReceivedWebpages) {
        ArrayList<TLRPC.Message> arrayList = (ArrayList<TLRPC.Message>) args[0];
        boolean updated = false;
        for (int a = 0; a < arrayList.size(); a++) {
            TLRPC.Message message = arrayList.get(a);
            long did = MessageObject.getDialogId(message);
            if (did != dialog_id && did != mergeDialogId) {
                continue;
            }
            MessageObject currentMessage = messagesDict[did == dialog_id ? 0 : 1].get(message.id);
            if (currentMessage != null) {
                currentMessage.messageOwner.media = new TLRPC.TL_messageMediaWebPage();
                currentMessage.messageOwner.media.webpage = message.media.webpage;
                currentMessage.generateThumbs(true);
                updated = true;
            }
        }
        if (updated) {
            updateVisibleRows();
            if (chatLayoutManager != null
                    && chatLayoutManager.findLastVisibleItemPosition() >= messages.size() - 1) {
                moveScrollToLastMessage();
            }
        }
    } else if (id == NotificationCenter.didReceivedWebpagesInUpdates) {
        if (foundWebPage != null) {
            HashMap<Long, TLRPC.WebPage> hashMap = (HashMap<Long, TLRPC.WebPage>) args[0];
            for (TLRPC.WebPage webPage : hashMap.values()) {
                if (webPage.id == foundWebPage.id) {
                    showReplyPanel(!(webPage instanceof TLRPC.TL_webPageEmpty), null, null, webPage, false,
                            true);
                    break;
                }
            }
        }
    } else if (id == NotificationCenter.messagesReadContent) {
        ArrayList<Long> arrayList = (ArrayList<Long>) args[0];
        boolean updated = false;
        for (int a = 0; a < arrayList.size(); a++) {
            long mid = arrayList.get(a);
            MessageObject currentMessage = messagesDict[mergeDialogId == 0 ? 0 : 1].get((int) mid);
            if (currentMessage != null) {
                currentMessage.setContentIsRead();
                updated = true;
            }
        }
        if (updated) {
            updateVisibleRows();
        }
    } else if (id == NotificationCenter.botInfoDidLoaded) {
        int guid = (Integer) args[1];
        if (classGuid == guid) {
            TLRPC.BotInfo info = (TLRPC.BotInfo) args[0];
            if (currentEncryptedChat == null) {
                if (!info.commands.isEmpty() && !ChatObject.isChannel(currentChat)) {
                    hasBotsCommands = true;
                }
                botInfo.put(info.user_id, info);
                if (chatAdapter != null) {
                    chatAdapter.notifyItemChanged(0);
                }
                if (mentionsAdapter != null && (!ChatObject.isChannel(currentChat)
                        || currentChat != null && currentChat.megagroup)) {
                    mentionsAdapter.setBotInfo(botInfo);
                }
                if (chatActivityEnterView != null) {
                    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
                }
            }
            updateBotButtons();
        }
    } else if (id == NotificationCenter.botKeyboardDidLoaded) {
        if (dialog_id == (Long) args[1]) {
            TLRPC.Message message = (TLRPC.Message) args[0];
            if (message != null && !userBlocked) {
                botButtons = new MessageObject(message, null, false);
                if (chatActivityEnterView != null) {
                    if (botButtons.messageOwner.reply_markup instanceof TLRPC.TL_replyKeyboardForceReply) {
                        SharedPreferences preferences = ApplicationLoader.applicationContext
                                .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                        if (preferences.getInt("answered_" + dialog_id, 0) != botButtons.getId()
                                && (replyingMessageObject == null
                                        || chatActivityEnterView.getFieldText() == null)) {
                            botReplyButtons = botButtons;
                            chatActivityEnterView.setButtons(botButtons);
                            showReplyPanel(true, botButtons, null, null, false, true);
                        }
                    } else {
                        if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
                            botReplyButtons = null;
                            showReplyPanel(false, null, null, null, false, true);
                        }
                        chatActivityEnterView.setButtons(botButtons);
                    }
                }
            } else {
                botButtons = null;
                if (chatActivityEnterView != null) {
                    if (replyingMessageObject != null && botReplyButtons == replyingMessageObject) {
                        botReplyButtons = null;
                        showReplyPanel(false, null, null, null, false, true);
                    }
                    chatActivityEnterView.setButtons(botButtons);
                }
            }
        }
    } else if (id == NotificationCenter.chatSearchResultsAvailable) {
        if (classGuid == (Integer) args[0]) {
            int messageId = (Integer) args[1];
            long did = (Long) args[3];
            if (messageId != 0) {
                scrollToMessageId(messageId, 0, true, did == dialog_id ? 0 : 1);
            }
            updateSearchButtons((Integer) args[2], (Integer) args[4], (Integer) args[5]);
        }
    } else if (id == NotificationCenter.didUpdatedMessagesViews) {
        SparseArray<SparseIntArray> channelViews = (SparseArray<SparseIntArray>) args[0];
        SparseIntArray array = channelViews.get((int) dialog_id);
        if (array != null) {
            boolean updated = false;
            for (int a = 0; a < array.size(); a++) {
                int messageId = array.keyAt(a);
                MessageObject messageObject = messagesDict[0].get(messageId);
                if (messageObject != null) {
                    int newValue = array.get(messageId);
                    if (newValue > messageObject.messageOwner.views) {
                        messageObject.messageOwner.views = newValue;
                        updated = true;
                    }
                }
            }
            if (updated) {
                updateVisibleRows();
            }
        }
    } else if (id == NotificationCenter.peerSettingsDidLoaded) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            updateSpamView();
        }
    } else if (id == NotificationCenter.newDraftReceived) {
        long did = (Long) args[0];
        if (did == dialog_id) {
            applyDraftMaybe(true);
        }
    }
}