Example usage for java.util ArrayList indexOf

List of usage examples for java.util ArrayList indexOf

Introduction

In this page you can find the example usage for java.util ArrayList indexOf.

Prototype

public int indexOf(Object o) 

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

@SuppressWarnings("nls")
private Operator genJoinReduceSinkChild(QB qb, ExprNodeDesc[] joinKeys, Operator<?> child, String[] srcs,
        int tag) throws SemanticException {

    Operator dummy = Operator.createDummy(); // dummy for backtracking
    dummy.setParentOperators(Arrays.asList(child));

    RowResolver inputRR = opParseCtx.get(child).getRowResolver();
    RowResolver outputRR = new RowResolver();
    ArrayList<String> outputColumns = new ArrayList<String>();
    ArrayList<ExprNodeDesc> reduceKeys = new ArrayList<ExprNodeDesc>();
    ArrayList<ExprNodeDesc> reduceKeysBack = new ArrayList<ExprNodeDesc>();

    // Compute join keys and store in reduceKeys
    for (ExprNodeDesc joinKey : joinKeys) {
        reduceKeys.add(joinKey);//w w w . jav  a 2s.  co  m
        reduceKeysBack.add(ExprNodeDescUtils.backtrack(joinKey, dummy, child));
    }

    // Walk over the input row resolver and copy in the output
    ArrayList<ExprNodeDesc> reduceValues = new ArrayList<ExprNodeDesc>();
    ArrayList<ExprNodeDesc> reduceValuesBack = new ArrayList<ExprNodeDesc>();
    Map<String, ExprNodeDesc> colExprMap = new HashMap<String, ExprNodeDesc>();

    List<ColumnInfo> columns = inputRR.getColumnInfos();
    int[] index = new int[columns.size()];
    for (int i = 0; i < columns.size(); i++) {
        ColumnInfo colInfo = columns.get(i);
        String[] nm = inputRR.reverseLookup(colInfo.getInternalName());
        String[] nm2 = inputRR.getAlternateMappings(colInfo.getInternalName());
        ExprNodeDesc expr = new ExprNodeColumnDesc(colInfo);

        // backtrack can be null when input is script operator
        ExprNodeDesc exprBack = ExprNodeDescUtils.backtrack(expr, dummy, child);
        int kindex;
        if (exprBack == null) {
            kindex = -1;
        } else if (ExprNodeDescUtils.isConstant(exprBack)) {
            kindex = reduceKeysBack.indexOf(exprBack);
        } else {
            kindex = ExprNodeDescUtils.indexOf(exprBack, reduceKeysBack);
        }
        if (kindex >= 0) {
            ColumnInfo newColInfo = new ColumnInfo(colInfo);
            newColInfo.setInternalName(Utilities.ReduceField.KEY + ".reducesinkkey" + kindex);
            newColInfo.setTabAlias(nm[0]);
            outputRR.put(nm[0], nm[1], newColInfo);
            if (nm2 != null) {
                outputRR.addMappingOnly(nm2[0], nm2[1], newColInfo);
            }
            index[i] = kindex;
            continue;
        }
        index[i] = -reduceValues.size() - 1;
        String outputColName = getColumnInternalName(reduceValues.size());

        reduceValues.add(expr);
        reduceValuesBack.add(exprBack);

        ColumnInfo newColInfo = new ColumnInfo(colInfo);
        newColInfo.setInternalName(Utilities.ReduceField.VALUE + "." + outputColName);
        newColInfo.setTabAlias(nm[0]);

        outputRR.put(nm[0], nm[1], newColInfo);
        if (nm2 != null) {
            outputRR.addMappingOnly(nm2[0], nm2[1], newColInfo);
        }
        outputColumns.add(outputColName);
    }
    dummy.setParentOperators(null);

    int numReds = -1;

    // Use only 1 reducer in case of cartesian product
    if (reduceKeys.size() == 0) {
        numReds = 1;
        String error = StrictChecks.checkCartesian(conf);
        if (error != null)
            throw new SemanticException(error);
    }

    ReduceSinkDesc rsDesc = PlanUtils.getReduceSinkDesc(reduceKeys, reduceValues, outputColumns, false, tag,
            reduceKeys.size(), numReds, AcidUtils.Operation.NOT_ACID);

    ReduceSinkOperator rsOp = (ReduceSinkOperator) putOpInsertMap(
            OperatorFactory.getAndMakeChild(rsDesc, new RowSchema(outputRR.getColumnInfos()), child), outputRR);
    List<String> keyColNames = rsDesc.getOutputKeyColumnNames();
    for (int i = 0; i < keyColNames.size(); i++) {
        colExprMap.put(Utilities.ReduceField.KEY + "." + keyColNames.get(i), reduceKeys.get(i));
    }
    List<String> valColNames = rsDesc.getOutputValueColumnNames();
    for (int i = 0; i < valColNames.size(); i++) {
        colExprMap.put(Utilities.ReduceField.VALUE + "." + valColNames.get(i), reduceValues.get(i));
    }

    rsOp.setValueIndex(index);
    rsOp.setColumnExprMap(colExprMap);
    rsOp.setInputAliases(srcs);
    return rsOp;
}

From source file:org.telegram.messenger.MessagesController.java

public boolean processUpdateArray(ArrayList<TLRPC.Update> updates, final ArrayList<TLRPC.User> usersArr,
        final ArrayList<TLRPC.Chat> chatsArr) {
    if (updates.isEmpty()) {
        return true;
    }//ww  w  .j av a  2 s.  co m
    long currentTime = System.currentTimeMillis();

    final HashMap<Long, ArrayList<MessageObject>> messages = new HashMap<Long, ArrayList<MessageObject>>();
    final ArrayList<TLRPC.Message> messagesArr = new ArrayList<TLRPC.Message>();
    final ArrayList<Integer> markAsReadMessages = new ArrayList<Integer>();
    final HashMap<Integer, Integer> markAsReadEncrypted = new HashMap<Integer, Integer>();
    final ArrayList<Integer> deletedMessages = new ArrayList<Integer>();
    final ArrayList<Long> printChanges = new ArrayList<Long>();
    final ArrayList<TLRPC.ChatParticipants> chatInfoToUpdate = new ArrayList<TLRPC.ChatParticipants>();
    final ArrayList<TLRPC.Update> updatesOnMainThread = new ArrayList<TLRPC.Update>();
    final ArrayList<TLRPC.TL_updateEncryptedMessagesRead> tasks = new ArrayList<TLRPC.TL_updateEncryptedMessagesRead>();
    final ArrayList<Integer> contactsIds = new ArrayList<Integer>();
    MessageObject lastMessage = null;

    boolean checkForUsers = true;
    ConcurrentHashMap<Integer, TLRPC.User> usersDict;
    ConcurrentHashMap<Integer, TLRPC.Chat> chatsDict;
    if (usersArr != null) {
        usersDict = new ConcurrentHashMap<Integer, TLRPC.User>();
        for (TLRPC.User user : usersArr) {
            usersDict.put(user.id, user);
        }
    } else {
        checkForUsers = false;
        usersDict = users;
    }
    if (chatsArr != null) {
        chatsDict = new ConcurrentHashMap<Integer, TLRPC.Chat>();
        for (TLRPC.Chat chat : chatsArr) {
            chatsDict.put(chat.id, chat);
        }
    } else {
        checkForUsers = false;
        chatsDict = chats;
    }

    if (usersArr != null || chatsArr != null) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (usersArr != null) {
                    for (TLRPC.User user : usersArr) {
                        users.put(user.id, user);
                        if (user.id == UserConfig.clientUserId) {
                            UserConfig.currentUser = user;
                        }
                    }
                }
                if (chatsArr != null) {
                    for (TLRPC.Chat chat : chatsArr) {
                        chats.put(chat.id, chat);
                    }
                }
            }
        });
    }

    int interfaceUpdateMask = 0;

    for (TLRPC.Update update : updates) {
        if (update instanceof TLRPC.TL_updateNewMessage) {
            TLRPC.TL_updateNewMessage upd = (TLRPC.TL_updateNewMessage) update;
            if (checkForUsers) {
                if (usersDict.get(upd.message.from_id) == null && users.get(upd.message.from_id) == null
                        || upd.message.to_id.chat_id != 0 && chatsDict.get(upd.message.to_id.chat_id) == null
                                && chats.get(upd.message.to_id.chat_id) == null) {
                    return false;
                }
            }
            messagesArr.add(upd.message);
            MessageObject obj = new MessageObject(upd.message, usersDict);
            if (obj.type == 11) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_AVATAR;
            } else if (obj.type == 10) {
                interfaceUpdateMask |= UPDATE_MASK_CHAT_NAME;
            }
            long uid;
            if (upd.message.to_id.chat_id != 0) {
                uid = -upd.message.to_id.chat_id;
            } else {
                if (upd.message.to_id.user_id == UserConfig.clientUserId) {
                    upd.message.to_id.user_id = upd.message.from_id;
                }
                uid = upd.message.to_id.user_id;
            }
            ArrayList<MessageObject> arr = messages.get(uid);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(uid, arr);
            }
            arr.add(obj);
            MessagesStorage.lastPtsValue = update.pts;
            if (upd.message.from_id != UserConfig.clientUserId && upd.message.to_id != null) {
                if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateMessageID) {
            //can't be here
        } else if (update instanceof TLRPC.TL_updateReadMessages) {
            markAsReadMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateDeleteMessages) {
            deletedMessages.addAll(update.messages);
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateRestoreMessages) {
            MessagesStorage.lastPtsValue = update.pts;
        } else if (update instanceof TLRPC.TL_updateUserTyping
                || update instanceof TLRPC.TL_updateChatUserTyping) {
            if (update.user_id != UserConfig.clientUserId) {
                long uid = -update.chat_id;
                if (uid == 0) {
                    uid = update.user_id;
                }
                ArrayList<PrintingUser> arr = printingUsers.get(uid);
                if (arr == null) {
                    arr = new ArrayList<PrintingUser>();
                    printingUsers.put(uid, arr);
                }
                boolean exist = false;
                for (PrintingUser u : arr) {
                    if (u.userId == update.user_id) {
                        exist = true;
                        u.lastTime = currentTime;
                        break;
                    }
                }
                if (!exist) {
                    PrintingUser newUser = new PrintingUser();
                    newUser.userId = update.user_id;
                    newUser.lastTime = currentTime;
                    arr.add(newUser);
                    if (!printChanges.contains(uid)) {
                        printChanges.add(uid);
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateChatParticipants) {
            interfaceUpdateMask |= UPDATE_MASK_CHAT_MEMBERS;
            chatInfoToUpdate.add(update.participants);
        } else if (update instanceof TLRPC.TL_updateUserStatus) {
            interfaceUpdateMask |= UPDATE_MASK_STATUS;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserName) {
            interfaceUpdateMask |= UPDATE_MASK_NAME;
            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
            interfaceUpdateMask |= UPDATE_MASK_AVATAR;
            MessagesStorage.Instance.clearUserPhotos(update.user_id);
            /*if (!(update.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) { DEPRECATED
            if (usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserUpdatedPhoto();
                newMessage.action.newUserPhoto = update.photo;
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;
                    
                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
             }*/

            updatesOnMainThread.add(update);
        } else if (update instanceof TLRPC.TL_updateContactRegistered) {
            if (enableJoined && usersDict.containsKey(update.user_id)) {
                TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
                newMessage.action = new TLRPC.TL_messageActionUserJoined();
                newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
                UserConfig.saveConfig(false);
                newMessage.unread = true;
                newMessage.date = update.date;
                newMessage.from_id = update.user_id;
                newMessage.to_id = new TLRPC.TL_peerUser();
                newMessage.to_id.user_id = UserConfig.clientUserId;
                newMessage.out = false;
                newMessage.dialog_id = update.user_id;

                messagesArr.add(newMessage);
                MessageObject obj = new MessageObject(newMessage, usersDict);
                ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(newMessage.dialog_id, arr);
                }
                arr.add(obj);
                if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                    if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
            //                if (!contactsIds.contains(update.user_id)) {
            //                    contactsIds.add(update.user_id);
            //                }
        } else if (update instanceof TLRPC.TL_updateContactLink) {
            if (update.my_link instanceof TLRPC.TL_contacts_myLinkContact
                    || update.my_link instanceof TLRPC.TL_contacts_myLinkRequested && update.my_link.contact) {
                int idx = contactsIds.indexOf(-update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(update.user_id);
                }
            } else {
                int idx = contactsIds.indexOf(update.user_id);
                if (idx != -1) {
                    contactsIds.remove(idx);
                }
                if (!contactsIds.contains(update.user_id)) {
                    contactsIds.add(-update.user_id);
                }
            }
        } else if (update instanceof TLRPC.TL_updateActivation) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewAuthorization) {
            TLRPC.TL_messageService newMessage = new TLRPC.TL_messageService();
            newMessage.action = new TLRPC.TL_messageActionLoginUnknownLocation();
            newMessage.action.title = update.device;
            newMessage.action.address = update.location;
            newMessage.local_id = newMessage.id = UserConfig.getNewMessageId();
            UserConfig.saveConfig(false);
            newMessage.unread = true;
            newMessage.date = update.date;
            newMessage.from_id = 333000;
            newMessage.to_id = new TLRPC.TL_peerUser();
            newMessage.to_id.user_id = UserConfig.clientUserId;
            newMessage.out = false;
            newMessage.dialog_id = 333000;

            messagesArr.add(newMessage);
            MessageObject obj = new MessageObject(newMessage, usersDict);
            ArrayList<MessageObject> arr = messages.get(newMessage.dialog_id);
            if (arr == null) {
                arr = new ArrayList<MessageObject>();
                messages.put(newMessage.dialog_id, arr);
            }
            arr.add(obj);
            if (newMessage.from_id != UserConfig.clientUserId && newMessage.to_id != null) {
                if (newMessage.dialog_id != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                    lastMessage = obj;
                }
            }
        } else if (update instanceof TLRPC.TL_updateNewGeoChatMessage) {
            //DEPRECATED
        } else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) {
            MessagesStorage.lastQtsValue = update.qts;
            TLRPC.Message message = decryptMessage(((TLRPC.TL_updateNewEncryptedMessage) update).message);
            if (message != null) {
                int cid = ((TLRPC.TL_updateNewEncryptedMessage) update).message.chat_id;
                messagesArr.add(message);
                MessageObject obj = new MessageObject(message, usersDict);
                long uid = ((long) cid) << 32;
                ArrayList<MessageObject> arr = messages.get(uid);
                if (arr == null) {
                    arr = new ArrayList<MessageObject>();
                    messages.put(uid, arr);
                }
                arr.add(obj);
                if (message.from_id != UserConfig.clientUserId && message.to_id != null) {
                    if (uid != openned_dialog_id || ApplicationLoader.lastPauseTime != 0) {
                        lastMessage = obj;
                    }
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedChatTyping) {
            long uid = ((long) update.chat_id) << 32;
            ArrayList<PrintingUser> arr = printingUsers.get(uid);
            if (arr == null) {
                arr = new ArrayList<PrintingUser>();
                printingUsers.put(uid, arr);
            }
            boolean exist = false;
            for (PrintingUser u : arr) {
                if (u.userId == update.user_id) {
                    exist = true;
                    u.lastTime = currentTime;
                    break;
                }
            }
            if (!exist) {
                PrintingUser newUser = new PrintingUser();
                newUser.userId = update.user_id;
                newUser.lastTime = currentTime;
                arr.add(newUser);
                if (!printChanges.contains(uid)) {
                    printChanges.add(uid);
                }
            }
        } else if (update instanceof TLRPC.TL_updateEncryptedMessagesRead) {
            markAsReadEncrypted.put(update.chat_id, Math.max(update.max_date, update.date));
            tasks.add((TLRPC.TL_updateEncryptedMessagesRead) update);
        } else if (update instanceof TLRPC.TL_updateChatParticipantAdd) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, false, update.inviter_id,
                    update.version);
        } else if (update instanceof TLRPC.TL_updateChatParticipantDelete) {
            MessagesStorage.Instance.updateChatInfo(update.chat_id, update.user_id, true, 0, update.version);
        } else if (update instanceof TLRPC.TL_updateDcOptions) {
            ConnectionsManager.Instance.updateDcSettings();
        } else if (update instanceof TLRPC.TL_updateEncryption) {
            final TLRPC.EncryptedChat newChat = update.chat;
            long dialog_id = ((long) newChat.id) << 32;
            TLRPC.EncryptedChat existingChat = encryptedChats.get(newChat.id);
            if (existingChat == null) {
                Semaphore semaphore = new Semaphore(0);
                ArrayList<TLObject> result = new ArrayList<TLObject>();
                MessagesStorage.Instance.getEncryptedChat(newChat.id, semaphore, result);
                try {
                    semaphore.acquire();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
                if (result.size() == 2) {
                    existingChat = (TLRPC.EncryptedChat) result.get(0);
                    TLRPC.User user = (TLRPC.User) result.get(1);
                    users.putIfAbsent(user.id, user);
                }
            }

            if (newChat instanceof TLRPC.TL_encryptedChatRequested && existingChat == null) {
                int user_id = newChat.participant_id;
                if (user_id == UserConfig.clientUserId) {
                    user_id = newChat.admin_id;
                }
                TLRPC.User user = users.get(user_id);
                if (user == null) {
                    user = usersDict.get(user_id);
                }
                newChat.user_id = user_id;
                final TLRPC.TL_dialog dialog = new TLRPC.TL_dialog();
                dialog.id = dialog_id;
                dialog.unread_count = 0;
                dialog.top_message = 0;
                dialog.last_message_date = update.date;

                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        dialogs_dict.put(dialog.id, dialog);
                        dialogs.add(dialog);
                        dialogsServerOnly.clear();
                        encryptedChats.put(newChat.id, newChat);
                        Collections.sort(dialogs, new Comparator<TLRPC.TL_dialog>() {
                            @Override
                            public int compare(TLRPC.TL_dialog tl_dialog, TLRPC.TL_dialog tl_dialog2) {
                                if (tl_dialog.last_message_date == tl_dialog2.last_message_date) {
                                    return 0;
                                } else if (tl_dialog.last_message_date < tl_dialog2.last_message_date) {
                                    return 1;
                                } else {
                                    return -1;
                                }
                            }
                        });
                        for (TLRPC.TL_dialog d : dialogs) {
                            if ((int) d.id != 0) {
                                dialogsServerOnly.add(d);
                            }
                        }
                        NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                    }
                });
                MessagesStorage.Instance.putEncryptedChat(newChat, user, dialog);
                acceptSecretChat(newChat);
            } else if (newChat instanceof TLRPC.TL_encryptedChat) {
                if (existingChat != null && existingChat instanceof TLRPC.TL_encryptedChatWaiting
                        && (existingChat.auth_key == null || existingChat.auth_key.length == 1)) {
                    newChat.a_or_b = existingChat.a_or_b;
                    newChat.user_id = existingChat.user_id;
                    processAcceptedSecretChat(newChat);
                }
            } else {
                final TLRPC.EncryptedChat exist = existingChat;
                Utilities.RunOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (exist != null) {
                            newChat.user_id = exist.user_id;
                            newChat.auth_key = exist.auth_key;
                            encryptedChats.put(newChat.id, newChat);
                        }
                        MessagesStorage.Instance.updateEncryptedChat(newChat);
                        NotificationCenter.Instance.postNotificationName(encryptedChatUpdated, newChat);
                    }
                });
            }
        }
    }
    if (!messages.isEmpty()) {
        for (HashMap.Entry<Long, ArrayList<MessageObject>> pair : messages.entrySet()) {
            Long key = pair.getKey();
            ArrayList<MessageObject> value = pair.getValue();
            boolean printChanged = updatePrintingUsersWithNewMessages(key, value);
            if (printChanged && !printChanges.contains(key)) {
                printChanges.add(key);
            }
        }
    }

    if (!printChanges.isEmpty()) {
        updatePrintingStrings();
    }

    final MessageObject lastMessageArg = lastMessage;
    final int interfaceUpdateMaskFinal = interfaceUpdateMask;

    if (!contactsIds.isEmpty()) {
        ContactsController.Instance.processContactsUpdates(contactsIds, usersDict);
    }

    if (!messagesArr.isEmpty()) {
        MessagesStorage.Instance.putMessages(messagesArr, true, true);
    }

    if (!messages.isEmpty() || !markAsReadMessages.isEmpty() || !deletedMessages.isEmpty()
            || !printChanges.isEmpty() || !chatInfoToUpdate.isEmpty() || !updatesOnMainThread.isEmpty()
            || !markAsReadEncrypted.isEmpty() || !contactsIds.isEmpty()) {
        Utilities.RunOnUIThread(new Runnable() {
            @Override
            public void run() {
                int updateMask = interfaceUpdateMaskFinal;

                boolean avatarsUpdate = false;
                if (!updatesOnMainThread.isEmpty()) {
                    ArrayList<TLRPC.User> dbUsers = new ArrayList<TLRPC.User>();
                    ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<TLRPC.User>();
                    for (TLRPC.Update update : updatesOnMainThread) {
                        TLRPC.User toDbUser = new TLRPC.User();
                        toDbUser.id = update.user_id;
                        TLRPC.User currentUser = users.get(update.user_id);
                        if (update instanceof TLRPC.TL_updateUserStatus) {
                            if (!(update.status instanceof TLRPC.TL_userStatusEmpty)) {
                                if (currentUser != null) {
                                    currentUser.id = update.user_id;
                                    currentUser.status = update.status;
                                    if (update.status instanceof TLRPC.TL_userStatusOnline) {
                                        currentUser.status.was_online = update.status.expires;
                                    } else if (update.status instanceof TLRPC.TL_userStatusOffline) {
                                        currentUser.status.expires = update.status.was_online;
                                    } else {
                                        currentUser.status.was_online = 0;
                                        currentUser.status.expires = 0;
                                    }
                                }
                                toDbUser.status = update.status;
                                dbUsersStatus.add(toDbUser);
                            }
                        } else if (update instanceof TLRPC.TL_updateUserName) {
                            if (currentUser != null) {
                                currentUser.first_name = update.first_name;
                                currentUser.last_name = update.last_name;
                            }
                            toDbUser.first_name = update.first_name;
                            toDbUser.last_name = update.last_name;
                            dbUsers.add(toDbUser);
                        } else if (update instanceof TLRPC.TL_updateUserPhoto) {
                            if (currentUser != null) {
                                currentUser.photo = update.photo;
                            }
                            avatarsUpdate = true;
                            toDbUser.photo = update.photo;
                            dbUsers.add(toDbUser);
                        }
                    }
                    MessagesStorage.Instance.updateUsers(dbUsersStatus, true, true, true);
                    MessagesStorage.Instance.updateUsers(dbUsers, false, true, true);
                }

                if (!messages.isEmpty()) {
                    for (HashMap.Entry<Long, ArrayList<MessageObject>> entry : messages.entrySet()) {
                        Long key = entry.getKey();
                        ArrayList<MessageObject> value = entry.getValue();
                        updateInterfaceWithMessages(key, value);
                    }
                    NotificationCenter.Instance.postNotificationName(dialogsNeedReload);
                }
                if (!markAsReadMessages.isEmpty()) {
                    for (Integer id : markAsReadMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.messageOwner.unread = false;
                        }
                    }
                    NotificationCenter.Instance.postNotificationName(messagesReaded, markAsReadMessages);
                }
                if (!markAsReadEncrypted.isEmpty()) {
                    for (HashMap.Entry<Integer, Integer> entry : markAsReadEncrypted.entrySet()) {
                        NotificationCenter.Instance.postNotificationName(messagesReadedEncrypted,
                                entry.getKey(), entry.getValue());
                        long dialog_id = (long) (entry.getKey()) << 32;
                        TLRPC.TL_dialog dialog = dialogs_dict.get(dialog_id);
                        if (dialog != null) {
                            MessageObject message = dialogMessage.get(dialog.top_message);
                            if (message != null && message.messageOwner.date <= entry.getValue()) {
                                message.messageOwner.unread = false;
                            }
                        }
                    }
                }
                if (!deletedMessages.isEmpty()) {
                    NotificationCenter.Instance.postNotificationName(messagesDeleted, deletedMessages);
                    for (Integer id : deletedMessages) {
                        MessageObject obj = dialogMessage.get(id);
                        if (obj != null) {
                            obj.deleted = true;
                        }
                    }
                }
                if (!printChanges.isEmpty()) {
                    updateMask |= UPDATE_MASK_USER_PRINT;
                }
                if (!contactsIds.isEmpty()) {
                    updateMask |= UPDATE_MASK_NAME;
                    updateMask |= UPDATE_MASK_USER_PHONE;
                }
                if (!chatInfoToUpdate.isEmpty()) {
                    for (TLRPC.ChatParticipants info : chatInfoToUpdate) {
                        MessagesStorage.Instance.updateChatInfo(info.chat_id, info, true);
                        NotificationCenter.Instance.postNotificationName(chatInfoDidLoaded, info.chat_id, info);
                    }
                }
                if (updateMask != 0) {
                    NotificationCenter.Instance.postNotificationName(updateInterfaces, updateMask);
                }
                if (lastMessageArg != null) {
                    showInAppNotification(lastMessageArg);
                }
            }
        });
    }

    if (!markAsReadMessages.isEmpty() || !markAsReadEncrypted.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsRead(markAsReadMessages, markAsReadEncrypted, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.markMessagesAsDeleted(deletedMessages, true);
    }
    if (!deletedMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithDeletedMessages(deletedMessages, true);
    }
    if (!markAsReadMessages.isEmpty()) {
        MessagesStorage.Instance.updateDialogsWithReadedMessages(markAsReadMessages, true);
    }
    if (!tasks.isEmpty()) {
        for (TLRPC.TL_updateEncryptedMessagesRead update : tasks) {
            MessagesStorage.Instance.createTaskForDate(update.chat_id, update.max_date, update.date, 1);
        }
    }

    return true;
}

From source file:org.fhaes.jsea.JSEAStatsFunctions.java

/**
 * TODO//from   ww  w  .j av a  2  s.  c  o m
 * 
 * @param titleForRun
 * @param outputFilePrefix
 * @param seedNumber
 * @param yearsPriorToEvent
 * @param yearsAfterTheEvent
 * @param numberOfSimulations
 * @param firstYearOfProcess
 * @param lastYearOfProcess
 * @param includeIncompleteEpochs
 * @param randomSampling
 * @param chronologyYears
 * @param chronologyActual
 * @param events
 * @param growth
 * @param save
 * @param usingSegmentation
 * @param segmentTable
 * @param chronologyFile
 * @param alphaLevel95
 * @param alphaLevel99
 * @param alphaLevel999
 */
public JSEAStatsFunctions(String titleForRun, String outputFilePrefix, Integer seedNumber,
        Integer yearsPriorToEvent, Integer yearsAfterTheEvent, Integer numberOfSimulations,
        Integer firstYearOfProcess, Integer lastYearOfProcess, boolean includeIncompleteEpochs,
        boolean randomSampling, ArrayList<Integer> chronologyYears, ArrayList<Double> chronologyActual,
        ArrayList<Integer> events, boolean growth, boolean save, boolean usingSegmentation,
        SegmentTable segmentTable, String chronologyFile, boolean alphaLevel95, boolean alphaLevel99,
        boolean alphaLevel999, boolean doZScore) {

    long begintime = System.currentTimeMillis();
    this.titleForRun = titleForRun;
    this.outputFilePrefix = outputFilePrefix;
    this.yearsPriorToEvent = yearsPriorToEvent;
    this.yearsAfterTheEvent = yearsAfterTheEvent;
    this.randomSampling = randomSampling;
    this.numberOfSimulations = numberOfSimulations;
    this.seedNumber = seedNumber;
    this.firstYearOfProcess = firstYearOfProcess;
    this.lastYearOfProcess = lastYearOfProcess;
    // this.excludeIncompleteEpochs = excludeIncompleteEpochs;
    this.includeIncompleteEpochs = includeIncompleteEpochs;
    this.chronologyYears = chronologyYears;
    this.chronologyActual = chronologyActual;
    this.events = events;
    this.isFirstIteration = true;
    this.save = save;
    this.growth = growth;
    this.usingSegmentation = usingSegmentation;
    this.segmentTable = segmentTable;
    this.chronologyFile = chronologyFile;
    this.alphaLevel95 = alphaLevel95;
    this.alphaLevel99 = alphaLevel99;
    this.alphaLevel999 = alphaLevel999;
    this.doZScore = doZScore;

    log.debug("this.titleForRun = " + titleForRun);
    log.debug("this.outputFilePrefix = " + outputFilePrefix);
    log.debug("this.yearsPriorToEvent = " + yearsPriorToEvent);
    log.debug("this.yearsAfterTheEvent = " + yearsAfterTheEvent);
    log.debug("this.randomSampling = " + randomSampling);
    log.debug("this.numberOfSimulations = " + numberOfSimulations);
    log.debug("this.seedNumber = " + seedNumber);
    log.debug("this.firstYearOfProcess = " + firstYearOfProcess);
    log.debug("this.lastYearOfProcess = " + lastYearOfProcess);
    // log.debug("this.excludeIncompleteEpochs = "+excludeIncompleteEpochs);
    log.debug("this.includeIncompleteEpochs = " + includeIncompleteEpochs);
    log.debug("this.chronologyYears = " + chronologyYears);
    log.debug("this.chronologyActual = " + chronologyActual);
    log.debug("this.events = " + events);
    log.debug("this.save = " + save);
    log.debug("this.growth = " + growth);
    log.debug("this.usingSegmentation = " + usingSegmentation);
    // log.debug("this.segmentTable = earliestYear " + segmentTable.getEarliestYear() + ", latestYear " + segmentTable.getLatestYear());
    log.debug("this.chronologyFile = " + chronologyFile);
    log.debug("this.alphaLevel95 = " + alphaLevel95);
    log.debug("this.alphaLevel99 = " + alphaLevel99);
    log.debug("this.alphaLevel999 = " + alphaLevel999);

    /*
     * Setting the three decimal format
     */
    DecimalFormat threePlacess = new DecimalFormat("0.000");

    /*
     * Creating the date of the run of the program
     */
    Date now = new Date();

    /*
     * Creating the files necessary (two txt files)
     */

    // File outputFile = new File(outputFilePrefix + ".out");
    // Writer wr;
    // String bigbuffer = "";

    report = new String("");
    actualTable = new String("");
    simulationTable = new String("");
    cdbuffer = new String("");
    pdfbufferA = new String("");
    pdfbufferB = new String("");
    pdfbufferpar1 = new String("");
    pdfbufferpar2 = new String("");

    /*
     * Converting Arraylists into arrays chronologyActual into chronoActual chronologyYears into yearsActual events into keyEvents
     */

    chronoActual = new Double[chronologyActual.size()];
    chronoActual = chronologyActual.toArray(chronoActual);
    yearsActual = new Integer[chronologyYears.size()];
    yearsActual = chronologyYears.toArray(yearsActual);

    Collections.sort(events);

    /*
     * Setting default values for first yearofprocess, lastyearofprocess recall the firstYearchrono is set as the default on the
     * firtYearOfProcess. also firstYearchrono is set as the default for firstYearsegment lastYearchrono is set as the default of the
     * lastYearOfProcess
     */

    if (firstYearOfProcess == 0) {
        firstYearOfProcess = yearsActual[0];
    }

    if (lastYearOfProcess == 0) {
        lastYearOfProcess = yearsActual[yearsActual.length];
    }

    if (numberOfSimulations == 0) {
        System.out.println("the number of simulations need to be set");
    }

    /*
     * 1. statistical Analysis of the whole time series chronology 2. statistical Analysis of the adjusted time series chronologyAdj 3.
     * statistical Analysis of the whole Event list events 4. print using the method printReport
     */

    // Statistical Analysis for the whole Climate Series

    DescriptiveStatistics stats = new DescriptiveStatistics();
    dchronoActual = new double[chronologyActual.size()];

    // Add the data from the array

    for (int i = 0; i < chronoActual.length; i++) {
        stats.addValue(chronoActual[i].doubleValue());
        dchronoActual[i] = chronoActual[i].doubleValue();
    }

    // Obtain the mean sensitivity

    meanSensitivity = 0;
    for (int i = 1; i < chronoActual.length; i++) {
        double senDenominator = Math.abs(dchronoActual[i]) + Math.abs(dchronoActual[i - 1]);
        if (senDenominator != 0) {
            meanSensitivity = meanSensitivity
                    + Math.abs(2 * (dchronoActual[i] - dchronoActual[i - 1])) / senDenominator;
        }
    }
    meanSensitivity = meanSensitivity / (dchronoActual.length - 1);

    /*
     * Obtain and display the general statistical information on the whole climate series.
     */

    mean = stats.getMean();
    std = stats.getStandardDeviation();
    median = StatUtils.percentile(dchronoActual, 50);
    kurt = stats.getKurtosis();
    skew = stats.getSkewness();

    /*
     * is segmentlength is different than 0 find the beginning and end year for each segment
     */

    firstYearsArray = new ArrayList<Integer>();
    lastYearsArray = new ArrayList<Integer>();

    // NO SEGMENTATION IS USED
    if (!usingSegmentation) {
        firstYearsArray.add(firstYearOfProcess);
        lastYearsArray.add(lastYearOfProcess);
    }

    // SEGMENTATION IS USED AND HAS BEEN DEFINED
    if (usingSegmentation) {
        for (int i = 0; i < segmentTable.tableModel.getSegments().size(); i++) {
            firstYearsArray.add(segmentTable.tableModel.getSegment(i).getFirstYear());
            lastYearsArray.add(segmentTable.tableModel.getSegment(i).getLastYear());
        }
    }

    /*
     * set up the loop for the typed of segmentation
     */

    /*
     * set the adjusted time series 1. set up the loop for the typed of segmentation 3.find the index of the first event in the actual
     * array. 2. adjust the series by yearsActual[indexofthefirstevent]-yearsPriortToEvent 3. adjust the series by
     * yearsActual[indexofthelasteventinseries]+yearsAfterTheEvent
     */

    for (int segmentIndex = 0; segmentIndex < firstYearsArray.size(); segmentIndex++) {
        beginingYearAdj = chronologyYears.get(0).intValue();
        lastYearAdj = chronologyYears.get(chronologyYears.size() - 1).intValue();

        firstYearOfProcess = firstYearsArray.get(segmentIndex);
        lastYearOfProcess = lastYearsArray.get(segmentIndex);
        if (firstYearOfProcess.intValue() > beginingYearAdj) {
            beginingYearAdj = firstYearOfProcess.intValue();
        }
        if (lastYearOfProcess.intValue() < lastYearAdj) {
            lastYearAdj = lastYearOfProcess.intValue();
        }

        /*
         * Obtain and display information on the Events actual Time span same as the adjusted. number of events. Events.size() and total
         * number of Events used. Mean years between events minimun differece between event years. *
         */

        keventsinadj = new ArrayList<Integer>();
        keventsinadjyeprior = new ArrayList<Integer>();
        keventsinadjyeafter = new ArrayList<Integer>();
        kevents = new ArrayList<Integer>();
        numberOfEventsinAdj = 0;
        for (int i = 0; i < events.size(); i++) {
            if (chronologyYears.contains(events.get(i))) {
                // System.out.println("the chronologyYears contains event " + i + "\t"
                // + beginingYearAdj + "\t" + lastYearAdj);
                if ((beginingYearAdj <= events.get(i).intValue())
                        && (events.get(i).intValue() <= lastYearAdj)) {
                    kevents.add(events.get(i));
                }
            }
            if ((chronologyYears.contains(events.get(i))) && (!includeIncompleteEpochs)) {
                if (((events.get(i).intValue() - beginingYearAdj) >= yearsPriorToEvent.intValue())
                        && ((lastYearAdj - events.get(i).intValue()) >= yearsAfterTheEvent.intValue())) {
                    numberOfEventsinAdj = numberOfEventsinAdj + 1;
                    keventsinadj.add(events.get(i));
                }
                ;
            }
            ;// end of exclude incomplete epochs
            if ((chronologyYears.contains(events.get(i))) && (includeIncompleteEpochs)) {
                if ((beginingYearAdj <= events.get(i).intValue())
                        && (events.get(i).intValue() <= lastYearAdj)) {
                    numberOfEventsinAdj = numberOfEventsinAdj + 1;
                    keventsinadj.add(events.get(i));
                    //
                    if ((events.get(i).intValue() - beginingYearAdj) < yearsPriorToEvent.intValue()) {
                        keventsinadjyeprior.add(events.get(i).intValue() - beginingYearAdj);
                    } else {
                        keventsinadjyeprior.add(yearsPriorToEvent);
                    }
                    if ((lastYearAdj - events.get(i).intValue()) < yearsAfterTheEvent.intValue()) {
                        keventsinadjyeafter.add(lastYearAdj - events.get(i).intValue());
                    } else {
                        keventsinadjyeafter.add(yearsAfterTheEvent.intValue());
                    }
                    //
                }
                ;
            }
            ; // end of include incomplete
        }
        ;// end of the loop for all events

        /*
         * set up if statement so that if we have two or less key events in the chronology we do not do anything
         */

        // System.out.println("size of kevents is " + kevents.size());
        if (kevents.size() >= 2) {
            keyEvents = new int[kevents.size()];
            for (int i = 0; i < kevents.size(); i++) {
                keyEvents[i] = kevents.get(i).intValue();
            }
            ;

            /*
             * Sorting keyEvents
             */

            Arrays.sort(keyEvents);

            if (keventsinadj.size() >= 2) {

                keyEventsAdj = new int[numberOfEventsinAdj];
                keyEventsAdjBeYear = new int[numberOfEventsinAdj];
                keyEventsAdjLaYear = new int[numberOfEventsinAdj];
                for (int i = 0; i < keventsinadj.size(); i++) {
                    keyEventsAdj[i] = keventsinadj.get(i).intValue();
                    keyEventsAdjBeYear[i] = keyEventsAdj[i] - yearsPriorToEvent.intValue();
                    keyEventsAdjLaYear[i] = keyEventsAdj[i] + yearsAfterTheEvent.intValue();
                }
                ;

                Arrays.sort(keyEventsAdj);
                // Calculate the difference between events load in array
                diffBetweenEvents = new double[keyEvents.length - 1];
                sumOfDiff = 0;
                for (int i = 1; i < keyEvents.length; i++) {
                    diffBetweenEvents[i - 1] = keyEvents[i] - keyEvents[i - 1];
                    sumOfDiff = sumOfDiff + diffBetweenEvents[i - 1];
                }
                ;

                // Calculate the mean difference between events =
                // sum(y(i)-y(i-1))/total number of differences

                meanDiffBetweenEvents = sumOfDiff / diffBetweenEvents.length;

                // adjusting the beginning year that that it account for the events
                // years
                // and the beginning year of the process etc

                beginingYearAdj = Math.max(beginingYearAdj, (keyEvents[0] - yearsPriorToEvent));
                lastYearAdj = Math.min(lastYearAdj, (keyEvents[keyEvents.length - 1] + yearsAfterTheEvent));

                DescriptiveStatistics statsAdj = new DescriptiveStatistics();

                chronoAdj = new double[lastYearAdj - beginingYearAdj + 1];

                // Add data from the array

                for (int i = beginingYearAdj; i < lastYearAdj + 1; i++) {
                    statsAdj.addValue(chronoActual[chronologyYears.indexOf(i)].doubleValue());
                    chronoAdj[i - beginingYearAdj] = chronoActual[chronologyYears.indexOf(i)].doubleValue();
                }
                ;

                // Obtain the mean sensativity

                meanSensitivityAdj = 0;
                for (int i = 1; i < chronoAdj.length; i++) {
                    double senDenominatorAdj = Math.abs(chronoAdj[i]) + Math.abs(chronoAdj[i - 1]);
                    if (senDenominatorAdj != 0) {
                        meanSensitivityAdj = meanSensitivityAdj
                                + Math.abs(2 * (chronoAdj[i] - chronoAdj[i - 1])) / senDenominatorAdj;
                    }
                }

                meanSensitivityAdj = meanSensitivityAdj / (chronoAdj.length - 1);

                /*
                 * Obtain and display the general statistical information on the whole time series data.
                 */

                meanAdj = statsAdj.getMean();
                stdAdj = statsAdj.getStandardDeviation();
                medianAdj = StatUtils.percentile(chronoAdj, 50);
                kurtAdj = statsAdj.getKurtosis();
                skewAdj = statsAdj.getSkewness();
                // new PearsonsCorrelation().correlation(chronoAdj, chronoAdj);
                double autoNumSum = 0.0;
                double autoDemSum = 0.0;
                System.out.println("the length of chronoAdj is " + chronoAdj.length);
                for (int j = 0; j < (chronoAdj.length - 1); j++) {
                    // System.out.println("j is: "+j + "mean is "+ meanAdj + "chronoadj is "+chronoAdj[j] );
                    autoNumSum = autoNumSum + (chronoAdj[j] - meanAdj) * (chronoAdj[j + 1] - meanAdj);
                }
                for (int j = 0; j < chronoAdj.length; j++) {
                    autoDemSum = autoDemSum + (chronoAdj[j] - meanAdj) * (chronoAdj[j] - meanAdj);
                }
                autocorrelationAdj = autoNumSum / autoDemSum;
                // autocorrelationAdj=new PearsonsCorrelation().correlation(chronoAdj, chronoAdj);
                System.out.println("the autocorrelation of the adjustchonology is: " + autocorrelationAdj);

                /*
                 * Calculate the statistical information per window of the Actual Events. load the values of the choronoActual per
                 * window in window into a two dimensional array calculate the mean per row calculate the standard deviation per row
                 * calculate end values of the confidence interval for 95%,99%.99.9% per row
                 */

                // Definition of the length of the window of interest.

                lengthOfWindow = yearsPriorToEvent + yearsAfterTheEvent + 1;

                // define the two dimensional array for the calculations of the Actual
                // Event windows stats

                meanByWindow = new double[lengthOfWindow];
                varianceByWindow = new double[lengthOfWindow];
                standardDevByWindow = new double[lengthOfWindow];
                maximunByWindow = new double[lengthOfWindow];
                minimunByWindow = new double[lengthOfWindow];
                eventWindowsAct = new double[lengthOfWindow][];
                eventWindowPattern = new int[lengthOfWindow][];
                Simnumdates = new int[lengthOfWindow];
                test = new ArrayList<Double>();
                for (int k = 0; k < lengthOfWindow; k++) {
                    eventWindowPattern[k] = new int[keventsinadj.size()];
                    int kWindow = k - yearsPriorToEvent.intValue();
                    for (int i = 0; i < keventsinadj.size(); i++) {
                        if ((beginingYearAdj <= (keventsinadj.get(i).intValue() + kWindow))
                                && ((keventsinadj.get(i).intValue() + kWindow) <= lastYearAdj)) {
                            test.add(chronologyActual
                                    .get(chronologyYears.indexOf(keventsinadj.get(i).intValue() + kWindow)));
                            eventWindowPattern[k][i] = 1;
                        } else {
                            eventWindowPattern[k][i] = 0;
                        }
                    }
                    Simnumdates[k] = test.size();
                    eventWindowsAct[k] = new double[test.size()]; // new line
                    for (int ij = 0; ij < test.size(); ij++) {
                        eventWindowsAct[k][ij] = test.get(ij).doubleValue();
                    }
                    test.clear();
                    meanByWindow[k] = StatUtils.mean(eventWindowsAct[k]);
                    varianceByWindow[k] = StatUtils.variance(eventWindowsAct[k]);
                    standardDevByWindow[k] = Math.sqrt(varianceByWindow[k]);
                    maximunByWindow[k] = StatUtils.max(eventWindowsAct[k]);
                    minimunByWindow[k] = StatUtils.min(eventWindowsAct[k]);
                } // end k loop
                Arrays.sort(Simnumdates);
                temp = Simnumdates[0];
                leftEndPoint = new double[lengthOfWindow][3];
                rightEndPoint = new double[lengthOfWindow][3];
                for (int i = 0; i < lengthOfWindow; i++) {
                    for (int j = 0; j < 3; j++) {
                        leftEndPoint[i][j] = meanByWindow[i] - stdDevMultiplier[j] * standardDevByWindow[i];
                        rightEndPoint[i][j] = meanByWindow[i] + stdDevMultiplier[j] * standardDevByWindow[i];
                    }
                }

                /*
                 * calculate the percentile Marks for simulation table
                 */

                percentileMark = new int[4];
                percentileMark[1] = (int) Math.max(Math.round(this.numberOfSimulations / 40.0), 1) - 1;
                percentileMark[3] = (int) Math.max(Math.round(this.numberOfSimulations / 200.0), 1) - 1;
                percentileMark[0] = this.numberOfSimulations - percentileMark[1] - 1;
                percentileMark[2] = this.numberOfSimulations - percentileMark[3] - 1;

                // System.out.println("percentailmarks "+percentileMark[0]+" , "
                // +percentileMark[1]+" , " + percentileMark[2]+" , " +
                // percentileMark[3]);

                // start the simulations: by selecting events.size() number of random
                // years

                Random myrand = new Random();
                myrand.setSeed(seedNumber);

                double[][] meanByWindowSim = new double[lengthOfWindow][this.numberOfSimulations];
                int[] eventYearSimulation = new int[keventsinadj.size()];// changed
                // keventsinadj.size()
                // by temp
                double[][] eventWindowsSims = new double[lengthOfWindow][];
                simulationtest = new ArrayList<Double>();

                /*
                 * Simulation Start
                 */
                System.out
                        .println("Before Simulation Time " + (System.currentTimeMillis() - begintime) / 1000F);
                for (int ii = 0; ii < this.numberOfSimulations; ii++) {
                    for (int i = 0; i < keventsinadj.size(); i++) {
                        // Here add the two if statement for include and exclude so the
                        // range of the selection of years
                        if (includeIncompleteEpochs) {
                            eventYearSimulation[i] = (beginingYearAdj + keventsinadjyeprior.get(i).intValue())
                                    + myrand.nextInt((lastYearAdj - keventsinadjyeafter.get(i).intValue())
                                            - (beginingYearAdj + keventsinadjyeprior.get(i).intValue()) + 1);
                        }
                        if (!includeIncompleteEpochs) {
                            eventYearSimulation[i] = (beginingYearAdj + 6)
                                    + myrand.nextInt((lastYearAdj - 4) - (beginingYearAdj + 6) + 1);
                        }

                    } // end i loop
                    Arrays.sort(eventYearSimulation);
                    // System.out.println("after selection of key events in sim " + ii + " time " + (System.currentTimeMillis() -
                    // start) / 1000F);
                    /*
                     * Once the events have been simulated build the two sised matrix (lengthOfWindow) by events.size()
                     */

                    for (int k = 0; k < lengthOfWindow; k++) {
                        eventWindowsSims[k] = new double[keventsinadj.size()];// new line
                        int kWindow = k - yearsPriorToEvent.intValue();
                        for (int i = 0; i < keventsinadj.size(); i++) {
                            if (eventWindowPattern[k][i] == 1) {
                                simulationtest.add(chronologyActual
                                        .get(chronologyYears.indexOf(eventYearSimulation[i] + kWindow)));
                            }
                        } // i loop
                        eventWindowsSims[k] = new double[simulationtest.size()]; // new
                        // line
                        for (int ij = 0; ij < simulationtest.size(); ij++) {
                            eventWindowsSims[k][ij] = simulationtest.get(ij).doubleValue();
                        } // edn ij loop
                        simulationtest.clear();
                        meanByWindowSim[k][ii] = StatUtils.mean(eventWindowsSims[k]);
                    } // end k loop numberofsimulation loop
                } // end simulatrion loop

                System.out.println("I am done with simulation");

                // calculate the mean of the means
                double sum = 0.0;
                meanMeanByWindow = new double[lengthOfWindow];
                varianceMeanByWindow = new double[lengthOfWindow];
                standardDevMeanByWindow = new double[lengthOfWindow];
                maxMeanByWindow = new double[lengthOfWindow];
                minMeanByWindow = new double[lengthOfWindow];
                double[] tempMeanMean = new double[this.numberOfSimulations];
                leftEndPointPer = new double[lengthOfWindow][2];
                rightEndPointPer = new double[lengthOfWindow][2];

                for (int i = 0; i < lengthOfWindow; i++) {
                    // int kWindow = i - yearsPriorToEvent.intValue();
                    for (int k = 0; k < this.numberOfSimulations; k++) {
                        // for(int k=0;k < (Integer)numberOfSimulations.intValue();k++){
                        if (k < 1) {
                            // /eSystem.out.println("on the " +i+","+k+" the value is " +
                            // meanByWindowSim[i][k]);
                        }
                        ;
                        tempMeanMean[k] = meanByWindowSim[i][k];
                        sum = sum + tempMeanMean[k];
                        // System.out.println("tempMeanMean is " + tempMeanMean[k]);
                    }
                    meanMeanByWindow[i] = StatUtils.mean(tempMeanMean);
                    varianceMeanByWindow[i] = StatUtils.variance(tempMeanMean);
                    standardDevMeanByWindow[i] = Math.sqrt(varianceMeanByWindow[i]);
                    Arrays.sort(tempMeanMean);
                    maxMeanByWindow[i] = StatUtils.max(tempMeanMean);
                    minMeanByWindow[i] = StatUtils.min(tempMeanMean);

                    leftEndPointPer[i][0] = tempMeanMean[percentileMark[1]];
                    rightEndPointPer[i][0] = tempMeanMean[percentileMark[0]];
                    leftEndPointPer[i][1] = tempMeanMean[percentileMark[3]];
                    rightEndPointPer[i][1] = tempMeanMean[percentileMark[2]];

                    // System.out.println("[ "+
                    // Math.round(leftEndPoint[i][j]*1000.0)/1000.0 + " , " +
                    // Math.round(rightEndPoint[i][j]*1000.0)/1000.0+"]");

                    // System.out.println("meanMeanByWindow is " + meanMeanByWindow[i]);
                    if (i < 1) {
                        // /eSystem.out.println("the window "+i+" has mean: " +
                        // Math.round(meanMeanByWindow[i]*1000.0)/1000.0);
                    }
                    ;
                    // System.out.println("the window "+i+" has variance: " +
                    // Math.round(varianceMeanByWindow[i]*1000.0)/1000.0);
                    // System.out.println("the window "+i+" has standard dev: " +
                    // Math.round(standardDevMeanByWindow[i]*1000.0)/1000.0);
                }
                ;// end of i loop
                 // }//end of ikj loop
                 // Calculate the confidence interval for 95%,99%,99.9%

                leftEndPointSim = new double[lengthOfWindow][3];
                rightEndPointSim = new double[lengthOfWindow][3];
                for (int i = 0; i < lengthOfWindow; i++) {
                    for (int j = 0; j < 3; j++) {
                        leftEndPointSim[i][j] = meanMeanByWindow[i]
                                - stdDevMultiplier[j] * standardDevMeanByWindow[i];
                        rightEndPointSim[i][j] = meanMeanByWindow[i]
                                + stdDevMultiplier[j] * standardDevMeanByWindow[i];
                        // System.out.println("[ "+
                        // Math.round(leftEndPoint[i][j]*1000.0)/1000.0 + " , " +
                        // Math.round(rightEndPoint[i][j]*1000.0)/1000.0+"]");
                    }
                }
                // }//end of ikj loop

                /*
                 * detecting which p-level was selected in gui
                 */
                if (alphaLevel95) {
                    alphaLevel = 0;
                } else if (alphaLevel99) {
                    alphaLevel = 1;
                } else {
                    alphaLevel = 2;
                }

                /*
                 * adding the chart and the creation on the buffer here
                 */

                // BarChartParametersModel m = new BarChartParametersModel(titleForRun, meanByWindow, lengthOfWindow, yearsPriorToEvent,
                // yearsAfterTheEvent, leftEndPointSim, rightEndPointSim, outputFilePrefix, alphaLevel, segmentIndex,
                // firstYearsArray.size(), firstYearsArray.get(segmentIndex), lastYearsArray.get(segmentIndex));

                BarChartParametersModel m = new BarChartParametersModel(titleForRun, meanByWindow,
                        lengthOfWindow, yearsPriorToEvent, yearsAfterTheEvent, leftEndPointSim,
                        rightEndPointSim, outputFilePrefix, alphaLevel, segmentIndex, firstYearsArray.size(),
                        beginingYearAdj, lastYearAdj);
                // m.setChart(new JSEABarChart(m).getChart());
                this.chartList.add(m);

                /*
                 * try { // ChartUtilities.saveChartAsJPEG(new File(outputFilePrefix+"chart"+ikj+ ".jpg"), chart, 500, 300);
                 * ChartUtilities.saveChartAsJPEG(new File(outputFilePrefix+"chart.jpg"), chart, 500, 300); } catch (IOException ex) {
                 * System.err.println(ex.getLocalizedMessage()); }
                 */

                // Date now = new Date();
                // System.out.println("the date today is: " + now);
                // adding the cdbuffer stuff
                log.debug("the value of the beginingyear of the adj crono is " + beginingYearAdj);
                String delim = ",";
                cdbuffer = cdbuffer + "Range:" + "\n";
                cdbuffer = cdbuffer + beginingYearAdj + delim + lastYearAdj + "\n";
                cdbuffer = cdbuffer + "Lags" + delim + "Events Mean" + delim + "95% CONF INT" + delim
                        + "95% CONF INT" + delim + "99% CONF INT" + delim + "99% CONF INT" + delim
                        + "99.9% CONF INT" + delim + "99.9% CONF INT" + delim + "\n";
                for (int i = 0; i < lengthOfWindow; i++) {
                    cdbuffer = cdbuffer + (i - yearsPriorToEvent.intValue()) + delim
                            + threePlacess.format(meanByWindow[i]) + delim
                            + threePlacess.format(leftEndPointSim[i][0]) + delim
                            + threePlacess.format(rightEndPointSim[i][0]) + delim
                            + threePlacess.format(leftEndPointSim[i][1]) + ","
                            + threePlacess.format(rightEndPointSim[i][1]) + delim
                            + threePlacess.format(leftEndPointSim[i][2]) + delim
                            + threePlacess.format(rightEndPointSim[i][2]) + "\n";
                }
                // adding the bigbuffer and pdfbufferpar1 stuff
                // Paragraph pdfbufferpar11 = new Paragraph( );
                report = report + "\n";
                report = report + "SUPERPOSED EPOCH ANALYSIS RESULTS" + "\n";
                report = report + "Date: " + now + "\n";
                report = report + "Name of the time series file: " + chronologyFile;
                pdfbufferpar1 = pdfbufferpar1 + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "SUPERPOSED EPOCH ANALYSIS RESULTS" + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "Date: " + now + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "Name of the time series file: " + chronologyFile;

                if (firstYearOfProcess.intValue() > chronologyYears.get(0).intValue()) {
                    report = report + "\n" + "First Year= " + firstYearOfProcess;
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "First Year= " + firstYearOfProcess;
                } else {
                    report = report + "\n" + "First Year= " + chronologyYears.get(0);
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "First Year= " + chronologyYears.get(0);
                }
                if (lastYearOfProcess.intValue() < chronologyYears.get(chronologyYears.size() - 1).intValue()) {
                    report = report + "\n" + "Last Year= " + lastYearOfProcess;
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "Last Year= " + lastYearOfProcess;
                } else {
                    report = report + "\n" + "Last Year= " + chronologyYears.get(chronologyYears.size() - 1);
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "Last Year= "
                            + chronologyYears.get(chronologyYears.size() - 1);
                }

                /*
                 * Display the general statistical information on the Adjusted time series data.
                 */
                report = report + "\n"
                        + "DESCRIPTIVE STATISTICS INFORMATION ABOUT THE ADJUSTED CONTINUOUS TIME SERIES: "
                        + "\n" + "\n";
                report = report + "\t" + "The adjusted time series RANGES from " + beginingYearAdj + " to "
                        + lastYearAdj + "\n";
                report = report + "\t" + "The NUMBER OF YEARS in the adjusted time series is "
                        + chronoAdj.length + "\n";
                report = report + "\t" + "MEAN of the adjusted time series is " + threePlacess.format(meanAdj)
                        + "\n";
                report = report + "\t" + "MEDIAN of the adjusted time series is "
                        + threePlacess.format(medianAdj) + "\n";
                report = report + "\t" + "MEAN SENSITIVITY for the adjusted time series is "
                        + threePlacess.format(meanSensitivityAdj) + "\n";
                report = report + "\t" + "STANDARD DEVIATION of the adjusted time series is "
                        + threePlacess.format(stdAdj) + "\n";
                report = report + "\t" + "SKEWNESS of the adjusted time series is "
                        + threePlacess.format(skewAdj) + "\n";
                report = report + "\t" + "KURTOSIS of the adjusted time series is  "
                        + threePlacess.format(kurtAdj) + "\n";
                report = report + "\t" + "First Order AUTOCORRELATION Index of the adjusted time series is  "
                        + threePlacess.format(autocorrelationAdj) + "\n";

                /*
                 * save the general statistical information on the Adjusted time series data in pdf fie.
                 */
                pdfbufferpar1 = pdfbufferpar1 + "\n"
                        + "DESCRIPTIVE STATISTICS INFORMATION ABOUT THE ADJUSTED CONTINUOUS TIME SERIES: "
                        + "\n" + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "The adjusted time series RANGES from " + beginingYearAdj
                        + " to " + lastYearAdj + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "The NUMBER OF YEARS in the adjusted time series is "
                        + chronoAdj.length + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "MEAN of the adjusted time series is "
                        + threePlacess.format(meanAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "MEDIAN of the adjusted time series is "
                        + threePlacess.format(medianAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "MEAN SENSITIVITY for the adjusted time series is "
                        + threePlacess.format(meanSensitivityAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "STANDARD DEVIATION of the adjusted time series is "
                        + threePlacess.format(stdAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "SKEWNESS of the adjusted time series is "
                        + threePlacess.format(skewAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "KURTOSIS of the adjusted time series is  "
                        + threePlacess.format(kurtAdj) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t"
                        + "First Order AUTOCORRELATION Index of the adjusted time series is  "
                        + threePlacess.format(autocorrelationAdj) + "\n";

                /*
                 * Display the general information on the Actual Event list.
                 */
                report = report + "\n" + "THE INFORMATION ON THE ACTUAL KEY EVENTS IS" + "\n" + "\n";
                report = report + "\t" + "Number of key events: " + keyEvents.length + "\n";
                report = report + "\t" + "Number of key events used in analysis: " + numberOfEventsinAdj + "\n";
                report = report + "\t" + "Mean years between events is "
                        + threePlacess.format(meanDiffBetweenEvents) + "\n";
                report = report + "\t" + "Minimum difference is " + StatUtils.min(diffBetweenEvents) + "\n";

                /*
                 * write the general information on the Actual Event list to pdf file.
                 */
                pdfbufferpar1 = pdfbufferpar1 + "\n" + "THE INFORMATION ON THE ACTUAL KEY EVENTS IS" + "\n"
                        + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "Number of key events: " + keyEvents.length + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "Number of key events used in analysis: "
                        + numberOfEventsinAdj + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "Mean years between events is "
                        + threePlacess.format(meanDiffBetweenEvents) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\t" + "Minimum difference is "
                        + StatUtils.min(diffBetweenEvents) + "\n";
                pdfbufferpar11.add(pdfbufferpar1);
                para1.add(pdfbufferpar11);
                printTableActFlag.add(true);

                /*
                 * Write out everything that goes into the actualTable.
                 */
                PdfPTable tableAct = new PdfPTable(7);

                if (isFirstIteration) {
                    String tempStrA = "";

                    if (alphaLevel95) {
                        tempStrA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 95% CONF INT ", " MIN ", " MAX ");
                    } else if (alphaLevel99) {
                        tempStrA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 99% CONF INT ", " MIN ", " MAX ");
                    } else if (alphaLevel999) {
                        tempStrA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 99.9% CONF INT ", " MIN ",
                                " MAX ");
                    }

                    report = report + tempStrA + "\n";
                    actualTable = actualTable + tempStrA.substring(1) + "\n";

                    PdfPCell cell00A = new PdfPCell(new Paragraph(" ADJ SEG "));
                    tableAct.addCell(cell00A);
                    PdfPCell cell01A = new PdfPCell(new Paragraph(" LAGS "));
                    tableAct.addCell(cell01A);
                    PdfPCell cell02A = new PdfPCell(new Paragraph(" MEAN "));
                    tableAct.addCell(cell02A);
                    PdfPCell cell03A = new PdfPCell(new Paragraph(" STA DEV "));
                    tableAct.addCell(cell03A);

                    if (alphaLevel95) {
                        PdfPCell cell04A = new PdfPCell(new Paragraph(" 95% CONF INT "));
                        tableAct.addCell(cell04A);
                    } else if (alphaLevel99) {
                        PdfPCell cell04A = new PdfPCell(new Paragraph(" 99% CONF INT "));
                        tableAct.addCell(cell04A);
                    } else if (alphaLevel999) {
                        PdfPCell cell04A = new PdfPCell(new Paragraph(" 99.9% CONF INT "));
                        tableAct.addCell(cell04A);
                    }

                    PdfPCell cell05A = new PdfPCell(new Paragraph("  MIN  "));
                    tableAct.addCell(cell05A);
                    PdfPCell cell06A = new PdfPCell(new Paragraph("  MAX  "));
                    tableAct.addCell(cell06A);
                }

                for (int i = 0; i < lengthOfWindow; i++) {
                    if (alphaLevel95) {
                        pdfbufferA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanByWindow[i]),
                                threePlacess.format(standardDevByWindow[i]),
                                "[" + threePlacess.format(leftEndPoint[i][0]) + ","
                                        + threePlacess.format(rightEndPoint[i][0]) + "]",
                                threePlacess.format(minimunByWindow[i]),
                                threePlacess.format(maximunByWindow[i]));
                    } else if (alphaLevel99) {
                        pdfbufferA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanByWindow[i]),
                                threePlacess.format(standardDevByWindow[i]),
                                "[" + threePlacess.format(leftEndPoint[i][1]) + ","
                                        + threePlacess.format(rightEndPoint[i][1]) + "]",
                                threePlacess.format(minimunByWindow[i]),
                                threePlacess.format(maximunByWindow[i]));
                    } else if (alphaLevel999) {
                        pdfbufferA = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanByWindow[i]),
                                threePlacess.format(standardDevByWindow[i]),
                                "[" + threePlacess.format(leftEndPoint[i][2]) + ","
                                        + threePlacess.format(rightEndPoint[i][2]) + "]",
                                threePlacess.format(minimunByWindow[i]),
                                threePlacess.format(maximunByWindow[i]));
                    }

                    report = report + pdfbufferA + "\n";
                    actualTable = actualTable + pdfbufferA.substring(1) + "\n";

                    PdfPCell cell00A = new PdfPCell(new Paragraph(
                            firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)));
                    tableAct.addCell(cell00A);
                    PdfPCell cell01A = new PdfPCell(new Paragraph((i - yearsPriorToEvent.intValue())));
                    tableAct.addCell(cell01A);
                    PdfPCell cell02A = new PdfPCell(new Paragraph(threePlacess.format(meanByWindow[i])));
                    tableAct.addCell(cell02A);
                    PdfPCell cell03A = new PdfPCell(new Paragraph(threePlacess.format(standardDevByWindow[i])));
                    tableAct.addCell(cell03A);

                    if (alphaLevel95) {
                        PdfPCell cell04A = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPoint[i][0]) + ","
                                        + threePlacess.format(rightEndPoint[i][0]) + "]"));
                        tableAct.addCell(cell04A);
                    } else if (alphaLevel99) {
                        PdfPCell cell04A = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPoint[i][1]) + ","
                                        + threePlacess.format(rightEndPoint[i][1]) + "]"));
                        tableAct.addCell(cell04A);
                    } else if (alphaLevel999) {
                        PdfPCell cell04A = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPoint[i][2]) + ","
                                        + threePlacess.format(rightEndPoint[i][2]) + "]"));
                        tableAct.addCell(cell04A);
                    }

                    PdfPCell cell05A = new PdfPCell(new Paragraph(threePlacess.format(minimunByWindow[i])));
                    tableAct.addCell(cell05A);
                    PdfPCell cell06A = new PdfPCell(new Paragraph(threePlacess.format(maximunByWindow[i])));
                    tableAct.addCell(cell06A);
                }

                printTableAct.add(tableAct);

                /*
                 * Display the general information on the Simulations. (Normality is assumed)
                 */
                report = report + "\n" + "SIMULATIONS RESULTS: " + "\n" + "\n";
                report = report + "\t" + "NUMBER OF SIMULATIONS is: " + this.numberOfSimulations + "\n";
                report = report + "\t" + "RANDOM SEED: " + seedNumber + "\n";

                /*
                 * Save the general information on the Simulations. (Normality is assumed) for the pdf file
                 */
                pdfbufferpar2 = pdfbufferpar2 + "\n" + "SIMULATIONS RESULTS: " + "\n" + "\n";
                pdfbufferpar2 = pdfbufferpar2 + "\t" + "NUMBER OF SIMULATIONS is: " + numberOfSimulations
                        + "\n";
                pdfbufferpar2 = pdfbufferpar2 + "\t" + "RANDOM SEED: " + seedNumber + "\n";
                pdfbufferpar12.add(pdfbufferpar2);
                para2.add(pdfbufferpar12);

                /*
                 * Write out everything that goes into the simulationTable.
                 */
                PdfPTable tableSim = new PdfPTable(7);

                if (isFirstIteration) {
                    String tempStrB = "";

                    if (alphaLevel95) {
                        tempStrB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 95% CONF INT ", " MIN ", " MAX ");
                    } else if (alphaLevel99) {
                        tempStrB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 99% CONF INT ", " MIN ", " MAX ");
                    } else if (alphaLevel999) {
                        tempStrB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                " ADJ SEG ", " LAGS ", " MEAN ", "STA DEV", " 99.9% CONF INT ", " MIN ",
                                " MAX ");
                    }

                    report = report + tempStrB + "\n";
                    simulationTable = simulationTable + tempStrB.substring(1) + "\n";

                    PdfPCell cell00B = new PdfPCell(new Paragraph(" ADJ SEG "));
                    tableSim.addCell(cell00B);
                    PdfPCell cell01B = new PdfPCell(new Paragraph(" LAGS "));
                    tableSim.addCell(cell01B);
                    PdfPCell cell02B = new PdfPCell(new Paragraph(" MEAN "));
                    tableSim.addCell(cell02B);
                    PdfPCell cell03B = new PdfPCell(new Paragraph(" STA DEV "));
                    tableSim.addCell(cell03B);

                    if (alphaLevel95) {
                        PdfPCell cell04B = new PdfPCell(new Paragraph(" 95% CONF INT "));
                        tableSim.addCell(cell04B);
                    } else if (alphaLevel99) {
                        PdfPCell cell04B = new PdfPCell(new Paragraph(" 99% CONF INT "));
                        tableSim.addCell(cell04B);
                    } else if (alphaLevel999) {
                        PdfPCell cell04B = new PdfPCell(new Paragraph(" 99.9% CONF INT "));
                        tableSim.addCell(cell04B);
                    }

                    PdfPCell cell05B = new PdfPCell(new Paragraph("  MIN  "));
                    tableSim.addCell(cell05B);
                    PdfPCell cell06B = new PdfPCell(new Paragraph("  MAX  "));
                    tableSim.addCell(cell06B);

                    isFirstIteration = false;
                }

                for (int i = 0; i < lengthOfWindow; i++) {
                    if (alphaLevel95) {
                        pdfbufferB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanMeanByWindow[i]),
                                threePlacess.format(standardDevMeanByWindow[i]),
                                "[" + threePlacess.format(leftEndPointSim[i][0]) + ","
                                        + threePlacess.format(rightEndPointSim[i][0]) + "]",
                                threePlacess.format(minMeanByWindow[i]),
                                threePlacess.format(maxMeanByWindow[i]));
                    } else if (alphaLevel99) {
                        pdfbufferB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanMeanByWindow[i]),
                                threePlacess.format(standardDevMeanByWindow[i]),
                                "[" + threePlacess.format(leftEndPointSim[i][1]) + ","
                                        + threePlacess.format(rightEndPointSim[i][1]) + "]",
                                threePlacess.format(minMeanByWindow[i]),
                                threePlacess.format(maxMeanByWindow[i]));
                    } else if (alphaLevel999) {
                        pdfbufferB = String.format(
                                "\t %-12s" + "\t %-8s" + "\t %-8s" + "\t %-8s" + "\t %-20s" + "\t %-8s"
                                        + "\t %-8s",
                                // (firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)),
                                beginingYearAdj + " - " + lastYearAdj, (i - yearsPriorToEvent.intValue()),
                                threePlacess.format(meanMeanByWindow[i]),
                                threePlacess.format(standardDevMeanByWindow[i]),
                                "[" + threePlacess.format(leftEndPointSim[i][2]) + ","
                                        + threePlacess.format(rightEndPointSim[i][2]) + "]",
                                threePlacess.format(minMeanByWindow[i]),
                                threePlacess.format(maxMeanByWindow[i]));
                    }

                    report = report + pdfbufferB + "\n";
                    simulationTable = simulationTable + pdfbufferB.substring(1) + "\n";

                    PdfPCell cell00B = new PdfPCell(new Paragraph(
                            firstYearsArray.get(segmentIndex) + " - " + lastYearsArray.get(segmentIndex)));
                    tableSim.addCell(cell00B);
                    PdfPCell cell01B = new PdfPCell(new Paragraph((i - yearsPriorToEvent.intValue())));
                    tableSim.addCell(cell01B);
                    PdfPCell cell02B = new PdfPCell(new Paragraph(threePlacess.format(meanMeanByWindow[i])));
                    tableSim.addCell(cell02B);
                    PdfPCell cell03B = new PdfPCell(
                            new Paragraph(threePlacess.format(standardDevMeanByWindow[i])));
                    tableSim.addCell(cell03B);

                    if (alphaLevel95) {
                        PdfPCell cell04B = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPointSim[i][0]) + ","
                                        + threePlacess.format(rightEndPointSim[i][0]) + "]"));
                        tableSim.addCell(cell04B);

                        // PdfPCell cell05B = new PdfPCell(new Paragraph("[" + threePlacess.format(leftEndPointPer[i][0]) + ","
                        // + threePlacess.format(rightEndPointPer[i][0]) + "]"));
                        // tableSim.addCell(cell05B);
                    } else if (alphaLevel99) {
                        PdfPCell cell04B = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPointSim[i][1]) + ","
                                        + threePlacess.format(rightEndPointSim[i][1]) + "]"));
                        tableSim.addCell(cell04B);

                        // PdfPCell cell05B = new PdfPCell(new Paragraph("[" + threePlacess.format(leftEndPointPer[i][0]) + ","
                        // + threePlacess.format(rightEndPointPer[i][0]) + "]"));
                        // tableSim.addCell(cell05B);
                    } else if (alphaLevel999) {
                        PdfPCell cell04B = new PdfPCell(
                                new Paragraph("[" + threePlacess.format(leftEndPointSim[i][2]) + ","
                                        + threePlacess.format(rightEndPointSim[i][2]) + "]"));
                        tableSim.addCell(cell04B);

                        // PdfPCell cell05B = new PdfPCell(new Paragraph("[" + threePlacess.format(leftEndPointPer[i][0]) + ","
                        // + threePlacess.format(rightEndPointPer[i][0]) + "]"));
                        // tableSim.addCell(cell05B);
                    }

                    PdfPCell cell06B = new PdfPCell(new Paragraph(threePlacess.format(minMeanByWindow[i])));
                    tableSim.addCell(cell06B);
                    PdfPCell cell07B = new PdfPCell(new Paragraph(threePlacess.format(maxMeanByWindow[i])));
                    tableSim.addCell(cell07B);
                }

                printTableSim.add(tableSim);

            } // end of if keventsinadj >=2

            else {
                cdbuffer = cdbuffer + "Range:" + "\n";
                cdbuffer = cdbuffer + beginingYearAdj + "," + lastYearAdj + "\n";
                cdbuffer = cdbuffer + "Segment: " + (segmentIndex + 1)
                        + "has not enough events to run the analysis" + "\n";

                // ADDED SO THAT BAD SEGMENTS CANNOT BE SELECTED FOR DISPLAY ON THE CHART
                segmentTable.tableModel.getSegment(segmentIndex).setBadSegmentFlag(true);

                printTableActFlag.add(false);
                pdfbufferpar1 = pdfbufferpar1 + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "SUPERPOSED EPOCH ANALYSIS RESULTS" + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "Date: " + now + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "Name of the time series file: " + chronologyFile + "\n";
                if (firstYearOfProcess.intValue() > chronologyYears.get(0).intValue()) {
                    report = report + "\n" + "The First year processed: " + firstYearOfProcess + "\n";
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "The First year processed: " + firstYearOfProcess
                            + "\n";
                } else {
                    report = report + "\n" + "The First year processed " + chronologyYears.get(0) + "\n";
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "The First year processed " + chronologyYears.get(0)
                            + "\n";
                }
                if (lastYearOfProcess.intValue() < chronologyYears.get(chronologyYears.size() - 1).intValue()) {
                    report = report + "\n" + "The last year of the process is " + lastYearOfProcess + "\n";
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "The last year of the process is "
                            + lastYearOfProcess + "\n";
                } else {
                    report = report + "\n" + "The last year of the process is "
                            + chronologyYears.get(chronologyYears.size() - 1) + "\n";
                    pdfbufferpar1 = pdfbufferpar1 + "\n" + "The last year of the process is "
                            + chronologyYears.get(chronologyYears.size() - 1) + "\n";
                }
                report = report
                        + "Not enough events within the window in the time series (or segment of the time series) to proceed with the analysis  "
                        + keventsinadj.size() + "\n";
                pdfbufferpar1 = pdfbufferpar1
                        + "Not enough events within the window in the time series (or segment of the time series) to proceed with the analysis  "
                        + keventsinadj.size() + "\n";
            }
            ;// end of else for if keventsinadd >=2
        } // end of if kevents >=2
        else {
            cdbuffer = cdbuffer + "Range:" + "\n";
            cdbuffer = cdbuffer + beginingYearAdj + "," + lastYearAdj + "\n";
            cdbuffer = cdbuffer + "Segement: " + (segmentIndex + 1)
                    + "has not enough events to run the analysis" + "\n";

            // ADDED SO THAT BAD SEGMENTS CANNOT BE SELECTED FOR DISPLAY ON THE CHART
            segmentTable.tableModel.getSegment(segmentIndex).setBadSegmentFlag(true);

            printTableActFlag.add(false);
            pdfbufferpar1 = pdfbufferpar1 + "\n";
            pdfbufferpar1 = pdfbufferpar1 + "SUPERPOSED EPOCH ANALYSIS RESULTS" + "\n";
            pdfbufferpar1 = pdfbufferpar1 + "Date: " + now + "\n";
            pdfbufferpar1 = pdfbufferpar1 + "Name of the time series file: " + chronologyFile + "\n";
            if (firstYearOfProcess.intValue() > chronologyYears.get(0).intValue()) {
                report = report + "\n" + "The First year processed: " + firstYearOfProcess + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\n" + "The First year processed: " + firstYearOfProcess + "\n";
            } else {
                report = report + "\n" + "The First year processed " + chronologyYears.get(0) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\n" + "The First year processed " + chronologyYears.get(0)
                        + "\n";
            }
            if (lastYearOfProcess.intValue() < chronologyYears.get(chronologyYears.size() - 1).intValue()) {
                report = report + "\n" + "The last year of the process is " + lastYearOfProcess + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\n" + "The last year of the process is " + lastYearOfProcess
                        + "\n";
            } else {
                report = report + "\n" + "The last year of the process is "
                        + chronologyYears.get(chronologyYears.size() - 1) + "\n";
                pdfbufferpar1 = pdfbufferpar1 + "\n" + "The last year of the process is "
                        + chronologyYears.get(chronologyYears.size() - 1) + "\n";
            }
            report = report
                    + "Not enough events in the time series (or segment of the time series) to proceed with the analysis "
                    + kevents.size() + "\n";
            pdfbufferpar1 = pdfbufferpar1
                    + "Not enough events in the time series (or segment of the time series) to proceed with the analysis "
                    + kevents.size() + "\n";
        }
        pdfbufferpar1 = "";
        pdfbufferpar2 = "";
    }
    ; // ending the huge loop ikj
      // ending of additions

}

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   www  .j a  v  a  2  s.  c  o  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) {
        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  www . j  a va 2  s  . 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) {

        //   (  ?  ?
        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);
        }
    }
}