Example usage for android.util SparseArray size

List of usage examples for android.util SparseArray size

Introduction

In this page you can find the example usage for android.util SparseArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of key-value mappings that this SparseArray currently stores.

Usage

From source file:fr.cph.chicago.xml.Xml.java

public final List<Eta> parseTrainsFollow(final String xml, final TrainData data) throws ParserException {
    InputStream is = new ByteArrayInputStream(xml.getBytes());
    SparseArray<TrainArrival> arrivals = null;
    try {/*from   ww w .  ja  v  a 2 s. c  o m*/
        parser.setInput(is, "UTF-8");
        int eventType = parser.getEventType();
        XmlArrivalTrainTag tag = null;
        Date tmst = null;
        Integer errCd = null;
        String errNum = null;
        String tagName = null;
        Integer staId = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_DOCUMENT) {
                arrivals = new SparseArray<TrainArrival>();
            } else if (eventType == XmlPullParser.START_TAG) {
                tagName = parser.getName();
                if (tagName.equals("tmst")) {
                    tag = XmlArrivalTrainTag.TMST;
                } else if (tagName.equals("errCd")) {
                    tag = XmlArrivalTrainTag.ERRCD;
                } else if (tagName.equals("errNm")) {
                    tag = XmlArrivalTrainTag.ERRNM;
                } else if (tagName.equals("eta")) {
                    tag = XmlArrivalTrainTag.ETA;
                } else {
                    tag = XmlArrivalTrainTag.OTHER;
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                tag = null;
            } else if (eventType == XmlPullParser.TEXT) {
                String text = parser.getText();
                switch (tag) {
                case ETA:
                    break;
                case OTHER:
                    if (tagName.equals("staId")) {
                        staId = Integer.valueOf(text);
                        TrainArrival arri = arrivals.get(staId, new TrainArrival());
                        arri.setErrorCode(errCd);
                        arri.setErrorMessage(errNum);
                        arri.setTimeStamp(tmst);
                        List<Eta> etas = arri.getEtas();
                        if (etas == null) {
                            etas = new ArrayList<Eta>();
                            arri.setEtas(etas);
                        }
                        Eta eta = new Eta();
                        Station station = data.getStation(Integer.valueOf(text));
                        eta.setStation(station);
                        etas.add(eta);

                        arrivals.append(staId, arri);
                    } else if (tagName.equals("stpId")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            Stop stop = data.getStop(Integer.valueOf(text));
                            currentEta.setStop(stop);
                        }
                    } else if (tagName.equals("staNm")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            Station station = currentEta.getStation();
                            station.setName(text);
                        }

                    } else if (tagName.equals("stpDe")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            Stop stop = currentEta.getStop();
                            stop.setDescription(text);
                        }
                    } else if (tagName.equals("rn")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setRunNumber(Integer.valueOf(text));
                        }
                    } else if (tagName.equals("rt")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            TrainLine line = TrainLine.fromXmlString(text);
                            currentEta.setRouteName(line);
                        }
                    } else if (tagName.equals("destSt")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            Integer i = Integer.valueOf(text);
                            currentEta.setDestSt(i);
                        }
                    } else if (tagName.equals("destNm")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setDestName(text);
                        }
                    } else if (tagName.equals("trDr")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setTrainRouteDirectionCode(Integer.valueOf(text));
                        }
                    } else if (tagName.equals("prdt")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setPredictionDate(dfTrain.parse(text));
                        }
                    } else if (tagName.equals("arrT")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setArrivalDepartureDate(dfTrain.parse(text));
                        }
                    } else if (tagName.equals("isApp")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setIsApp(BooleanUtils.toBoolean(Integer.valueOf(text)));
                        }
                    } else if (tagName.equals("isSch")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setIsSch(BooleanUtils.toBoolean(Integer.valueOf(text)));
                        }
                    } else if (tagName.equals("isDly")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setIsDly(BooleanUtils.toBoolean(Integer.valueOf(text)));
                        }
                    } else if (tagName.equals("isFlt")) {
                        TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setIsFlt(BooleanUtils.toBoolean(Integer.valueOf(text)));
                        }
                    }
                    break;
                case TMST:
                    tmst = dfTrain.parse(text);
                    break;
                case ERRCD:
                    errCd = Integer.valueOf(text);
                    break;
                case ERRNM:
                    errNum = text;
                    break;
                default:
                    break;
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        throw new ParserException(TrackerException.ERROR, e);
    } catch (ParseException e) {
        throw new ParserException(TrackerException.ERROR, e);
    } catch (IOException e) {
        throw new ParserException(TrackerException.ERROR, e);
    }
    List<Eta> res = new ArrayList<Eta>();
    int index = 0;
    while (index < arrivals.size()) {
        TrainArrival arri = arrivals.valueAt(index++);
        List<Eta> etas = arri.getEtas();
        if (etas != null && etas.size() != 0) {
            res.add(etas.get(0));
        }
    }
    Collections.sort(res);
    return res;
}

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*/ });
            }/*from   ww  w . j a v  a 2s.  c om*/
            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 .ja va2s .  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);
        }
    }
}

From source file:fr.cph.chicago.parser.XmlParser.java

@NonNull
public final synchronized List<Eta> parseTrainsFollow(@NonNull final InputStream is,
        @NonNull final TrainData data) throws ParserException {
    SparseArray<TrainArrival> arrivals = new SparseArray<>();
    try {//w w w.j  a  v a 2 s  . c om
        parser.setInput(is, "UTF-8");
        int eventType = parser.getEventType();
        XmlArrivalTrainTag tag = null;
        //         Date tmst = null;
        //         Integer errCd = null;
        //         String errNum = null;
        String tagName = null;
        Integer staId = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                tagName = parser.getName();
                switch (tagName) {
                case "tmst":
                    tag = XmlArrivalTrainTag.TMST;
                    break;
                case "errCd":
                    tag = XmlArrivalTrainTag.ERRCD;
                    break;
                case "errNm":
                    tag = XmlArrivalTrainTag.ERRNM;
                    break;
                case "eta":
                    tag = XmlArrivalTrainTag.ETA;
                    break;
                default:
                    tag = XmlArrivalTrainTag.OTHER;
                    break;
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                tag = null;
            } else if (eventType == XmlPullParser.TEXT) {
                String text = parser.getText();
                switch (tag) {
                case ETA:
                    break;
                case OTHER:
                    switch (tagName) {
                    case "staId": {
                        staId = Integer.parseInt(text);
                        final TrainArrival arri = arrivals.get(staId, new TrainArrival());
                        //arri.setErrorCode(errCd);
                        //arri.setErrorMessage(errNum);
                        //arri.setTimeStamp(tmst);
                        List<Eta> etas = arri.getEtas();
                        if (etas == null) {
                            etas = new ArrayList<>();
                            arri.setEtas(etas);
                        }
                        final Eta eta = new Eta();
                        final Optional<Station> station = data.getStation(Integer.parseInt(text));
                        eta.setStation(station.orElse(new Station()));
                        etas.add(eta);

                        arrivals.append(staId, arri);
                        break;
                    }
                    case "stpId": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            final Stop stop = data.getStop(Integer.parseInt(text));
                            currentEta.setStop(stop);
                        }
                        break;
                    }
                    case "staNm": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            final Station station = currentEta.getStation();
                            station.setName(text);
                        }
                        break;
                    }
                    case "stpDe": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            final Stop stop = currentEta.getStop();
                            stop.setDescription(text);
                        }
                        break;
                    }
                    case "rn": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setRunNumber(Integer.parseInt(text));
                        }
                        break;
                    }
                    case "rt": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            final TrainLine line = TrainLine.fromXmlString(text);
                            currentEta.setRouteName(line);
                        }
                        break;
                    }
                    case "destSt": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            final Integer i = Integer.parseInt(text);
                            currentEta.setDestSt(i);
                        }
                        break;
                    }
                    case "destNm": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setDestName(text);
                        }
                        break;
                    }
                    case "trDr": {
                        //                     final TrainArrival arri = arrivals.get(staId, null);
                        //                     if (arri != null) {
                        //                        final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                        //                        currentEta.setTrainRouteDirectionCode(Integer.parseInt(text));
                        //                     }
                        break;
                    }
                    case "prdt": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setPredictionDate(simpleDateFormatTrain.parse(text));
                        }
                        break;
                    }
                    case "arrT": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setArrivalDepartureDate(simpleDateFormatTrain.parse(text));
                        }
                        break;
                    }
                    case "isApp": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setApp(Util.textNumberToBoolean(text));
                        }
                        break;
                    }
                    case "isSch": {
                        //                     final TrainArrival arri = arrivals.get(staId, null);
                        //                     if (arri != null) {
                        //                        final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                        //                        currentEta.setIsSch(Util.textNumberToBoolean(text));
                        //                     }
                        break;
                    }
                    case "isDly": {
                        final TrainArrival arri = arrivals.get(staId, null);
                        if (arri != null) {
                            final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                            currentEta.setDly(Util.textNumberToBoolean(text));
                        }
                        break;
                    }
                    case "isFlt": {
                        //                     final TrainArrival arri = arrivals.get(staId, null);
                        //                     if (arri != null) {
                        //                        final Eta currentEta = arri.getEtas().get(arri.getEtas().size() - 1);
                        //                        currentEta.setIsFlt(Util.textNumberToBoolean(text));
                        //                     }
                        break;
                    }
                    }
                    break;
                case TMST:
                    //tmst = simpleDateFormatTrain.parse(text);
                    break;
                case ERRCD:
                    //errCd = Integer.parseInt(text);
                    break;
                case ERRNM:
                    //errNum = text;
                    break;
                default:
                    break;
                }
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException | ParseException | IOException e) {
        throw new ParserException(TrackerException.ERROR, e);
    } finally {
        IOUtils.closeQuietly(is);
    }
    final List<Eta> res = new ArrayList<>();
    int index = 0;
    while (index < arrivals.size()) {
        final TrainArrival arri = arrivals.valueAt(index++);
        final List<Eta> etas = arri.getEtas();
        if (etas != null && etas.size() != 0) {
            res.add(etas.get(0));
        }
    }
    Collections.sort(res);
    return res;
}