Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

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

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:StreamFlusher.java

private void cartProdWhereMixed(ArrayList<String> listOfVarNames, ArrayList<ArrayList<Fst>> listOfListOfFst,
        ArrayList<RuleLocalVarSetting> current, int k, ArrayList<ArrayList<RuleLocalVarSetting>> result) {
    if (k == listOfListOfFst.size()) {
        result.add(new ArrayList<RuleLocalVarSetting>(current));
    } else {//from   w  w  w .ja  va  2 s  .  c  om
        for (int j = 0; j < listOfListOfFst.get(k).size(); j++) {
            current.set(k, new RuleLocalVarSetting(listOfVarNames.get(k), listOfListOfFst.get(k).get(j)));
            cartProdWhereMixed(listOfVarNames, listOfListOfFst, current, k + 1, result);
        }
    }
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public LossollarbeitsplanDto[] getAlleOffenenZeiternFuerStueckrueckmeldung(Integer personalIId,
        TheClientDto theClientDto) {// w  w  w.j av a 2  s  .  c  om

    ArrayList<LossollarbeitsplanDto> alDaten = new ArrayList<LossollarbeitsplanDto>();
    HashMap ids = new HashMap();
    try {

        Integer taetigkeitIId_Kommt = getZeiterfassungFac()
                .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_KOMMT, theClientDto).getIId();
        Integer taetigkeitIId_Geht = getZeiterfassungFac()
                .taetigkeitFindByCNr(ZeiterfassungFac.TAETIGKEIT_GEHT, theClientDto).getIId();

        Session session = FLRSessionFactory.getFactory().openSession();
        org.hibernate.Criteria liste = session.createCriteria(FLRZeitdaten.class);
        liste.add(Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_PERSONAL_I_ID, personalIId));

        liste.add(Restrictions.or(
                Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_TAETIGKEIT_I_ID, taetigkeitIId_Kommt),
                Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_TAETIGKEIT_I_ID, taetigkeitIId_Geht)));
        liste.add(Expression.lt(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT,
                new Timestamp(System.currentTimeMillis())));

        liste.add(
                Expression.eq(ZeiterfassungFac.FLR_ZEITDATEN_B_AUTOMATIKBUCHUNG, Helper.boolean2Short(false)));

        liste.addOrder(Order.desc(ZeiterfassungFac.FLR_ZEITDATEN_T_ZEIT));
        liste.setMaxResults(1);
        List<?> letztesKommt = liste.list();

        Iterator it = letztesKommt.iterator();

        Timestamp tVon = Helper.cutTimestamp(new Timestamp(System.currentTimeMillis()));

        if (it.hasNext()) {
            tVon = new Timestamp(((FLRZeitdaten) it.next()).getT_zeit().getTime());
        }

        boolean bTheoretischeIstZeit = false;

        try {
            ParametermandantDto parameterIstZeit = (ParametermandantDto) getParameterFac().getMandantparameter(
                    theClientDto.getMandant(), ParameterFac.KATEGORIE_PERSONAL,
                    ParameterFac.PARAMETER_THEORETISCHE_IST_ZEIT_RECHNUNG);

            bTheoretischeIstZeit = ((Boolean) parameterIstZeit.getCWertAsObject());

        } catch (RemoteException ex5) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER, ex5);
        }

        ZeitdatenDto[] dtos = getZeiterfassungFac().zeitdatenFindZeitdatenEinesTagesUndEinerPerson(personalIId,
                tVon, new Timestamp(System.currentTimeMillis()));

        boolean bRuestenSchonVorhanden = false;

        for (int i = dtos.length - 1; i >= 0; i--) {
            if (dtos[i].getCBelegartnr() != null && dtos[i].getIBelegartid() != null) {

                if (dtos[i].getCBelegartnr().equals(LocaleFac.BELEGART_LOS)
                        && dtos[i].getIBelegartpositionid() != null) {

                    try {
                        Lossollarbeitsplan lossollarbeitsplan = em.find(Lossollarbeitsplan.class,
                                dtos[i].getIBelegartpositionid());
                        if (lossollarbeitsplan != null) {
                            if (!Helper.short2boolean(lossollarbeitsplan.getBNurmaschinenzeit())
                                    && !Helper.short2boolean(lossollarbeitsplan.getBFertig())) {
                                LossollarbeitsplanDto sollDto = assembleLossollarbeitsplanDto(
                                        lossollarbeitsplan);

                                // PJ 16233
                                if (bTheoretischeIstZeit) {
                                    if (!ids.containsKey(sollDto.getIId())) {
                                        // PJ 16035 Ruesten nur das letzte
                                        if (sollDto.getAgartCNr() == null) {
                                            if (bRuestenSchonVorhanden == false) {
                                                bRuestenSchonVorhanden = true;
                                                alDaten.add(sollDto);
                                                ids.put(sollDto.getIId(), sollDto.getIId());
                                            }
                                        } else {
                                            alDaten.add(sollDto);
                                            ids.put(sollDto.getIId(), sollDto.getIId());
                                        }

                                    }
                                } else {
                                    alDaten.add(sollDto);
                                }
                            }
                        }

                    } catch (NoResultException fe) {
                        // keiner da
                    }
                }
            }
        }

        // nun nach Losnr und AG sortieren
        // Nach Fertigungsgruppe sortieren
        for (int k = alDaten.size() - 1; k > 0; --k) {
            for (int j = 0; j < k; ++j) {
                LossollarbeitsplanDto a1 = (LossollarbeitsplanDto) alDaten.get(j);
                LossollarbeitsplanDto a2 = (LossollarbeitsplanDto) alDaten.get(j + 1);

                LosDto l1 = losFindByPrimaryKey(a1.getLosIId());
                LosDto l2 = losFindByPrimaryKey(a2.getLosIId());

                String s1 = l1.getCNr();

                if (a1.getIUnterarbeitsgang() != null) {
                    s1 += Helper.fitString2LengthAlignRight(a1.getIUnterarbeitsgang() + "", 10, ' ');
                } else {
                    s1 += Helper.fitString2LengthAlignRight("", 10, ' ');
                }
                s1 += Helper.fitString2LengthAlignRight(a1.getIArbeitsgangnummer() + "", 10, ' ');

                String s2 = l2.getCNr();
                if (a2.getIUnterarbeitsgang() != null) {
                    s2 += Helper.fitString2LengthAlignRight(a2.getIUnterarbeitsgang() + "", 10, ' ');
                } else {
                    s2 += Helper.fitString2LengthAlignRight("", 10, ' ');
                }
                s2 += Helper.fitString2LengthAlignRight(a2.getIArbeitsgangnummer() + "", 10, ' ');

                if (s1.compareTo(s2) > 0) {
                    alDaten.set(j, a2);
                    alDaten.set(j + 1, a1);
                }
            }

        }

    } catch (RemoteException e) {
        throwEJBExceptionLPRespectOld(e);
    }

    LossollarbeitsplanDto[] returnArray = new LossollarbeitsplanDto[alDaten.size()];
    return (LossollarbeitsplanDto[]) alDaten.toArray(returnArray);
}

From source file:imitationNLG.SFX.java

public void createLists(File dataFile) {
    try {/*  w  w w  . j  a  va2  s.  c  o  m*/
        predicates = new ArrayList<>();
        attributes = new HashMap<>();
        attributeValuePairs = new HashMap<>();
        valueAlignments = new HashMap<>();

        String str = new String();
        boolean begin = false;
        try (BufferedReader br = new BufferedReader(new FileReader(dataFile))) {
            String s;
            while ((s = br.readLine()) != null) {
                if (s.startsWith("[")) {
                    begin = true;
                }
                if (begin) {
                    str += s;
                }
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex);
        }

        JSONArray overArray = new JSONArray(str);

        for (int o = 0; o < overArray.length(); o++) {
            JSONArray arr = overArray.getJSONObject(o).getJSONArray("dial");
            for (int i = 0; i < arr.length(); i++) {
                String MRstr = "";
                String ref = "";
                MRstr = arr.getJSONObject(i).getJSONObject("S").getString("dact");
                ref = arr.getJSONObject(i).getJSONObject("S").getString("ref").replaceAll("-s", "s");

                if ((MRstr.startsWith("inform(") || MRstr.startsWith("inform_only")
                        || MRstr.startsWith("inform_no_match(") || MRstr.startsWith("?confirm(")
                        || MRstr.startsWith("?select(") || MRstr.startsWith("?request(")
                        || MRstr.startsWith("?reqmore(") || MRstr.startsWith("goodbye(")) && !ref.isEmpty()) {
                    String predicate = MRstr.substring(0, MRstr.indexOf("("));
                    if (!predicates.contains(predicate) && predicate != null) {
                        predicates.add(predicate);

                        if (!attributes.containsKey(predicate)) {
                            attributes.put(predicate, new HashSet<String>());
                        }
                        if (!datasetInstances.containsKey(predicate)) {
                            datasetInstances.put(predicate, new ArrayList<DatasetInstance>());
                        }
                    }

                    String attributesStr = MRstr.substring(MRstr.indexOf('(') + 1, MRstr.length() - 1);
                    HashMap<String, HashSet<String>> attributeValues = new HashMap<>();
                    if (!attributesStr.isEmpty()) {
                        HashMap<String, Integer> attrXIndeces = new HashMap<>();

                        String[] args = attributesStr.split(";");
                        if (attributesStr.contains("|")) {
                            System.out.println(attributesStr);
                            System.exit(0);
                        }
                        for (String arg : args) {
                            String attr = "";
                            String value = "";
                            if (arg.contains("=")) {
                                String[] subAttr = arg.split("=");
                                value = subAttr[1].toLowerCase();
                                attr = subAttr[0].toLowerCase().replaceAll("_", "");
                            } else {
                                attr = arg.replaceAll("_", "");
                            }
                            if (!attributes.get(predicate).contains(attr)) {
                                attributes.get(predicate).add(attr);
                            }
                            if (!attributeValues.containsKey(attr)) {
                                attributeValues.put(attr, new HashSet<String>());
                            }
                            if (value.isEmpty()) {
                                value = attr;
                            }

                            if (value.startsWith("\'")) {
                                value = value.substring(1, value.length() - 1);
                            }
                            if (value.toLowerCase().startsWith("x")) {
                                int index = 0;
                                if (!attrXIndeces.containsKey(attr)) {
                                    attrXIndeces.put(attr, 1);
                                } else {
                                    index = attrXIndeces.get(attr);
                                    attrXIndeces.put(attr, index + 1);
                                }
                                value = "x" + index;
                            }
                            if (value.isEmpty()) {
                                System.out.println("EMPTY VALUE");
                                System.exit(0);
                            }

                            attributeValues.get(attr).add(value.trim().toLowerCase());
                        }
                        for (String attr : attributeValues.keySet()) {
                            if (attributeValues.get(attr).contains("yes")
                                    && attributeValues.get(attr).contains("no")) {
                                System.out.println(MRstr);
                                System.out.println(attributeValues);
                                System.exit(0);
                            }
                        }
                    }

                    //REF
                    //DELEXICALIZATION
                    HashMap<String, HashMap<String, Integer>> attrValuePriorities = new HashMap<>();
                    HashMap<String, HashSet<String>> delexAttributeValues = new HashMap<>();
                    int prio = 0;
                    for (String attr : attributeValues.keySet()) {
                        if (!attr.isEmpty()) {
                            delexAttributeValues.put(attr, new HashSet<String>());
                            if (attr.equals("name") || attr.equals("type") || attr.equals("pricerange")
                                    || attr.equals("price") || attr.equals("phone") || attr.equals("address")
                                    || attr.equals("postcode") || attr.equals("area") || attr.equals("near")
                                    || attr.equals("food") || attr.equals("count")
                                    || attr.equals("goodformeal")) {
                                attrValuePriorities.put(attr, new HashMap<String, Integer>());
                                for (String value : attributeValues.get(attr)) {
                                    if (!value.equals("dont_care") && !value.equals("none")
                                            && !value.equals("empty") && !value.equals(attr)) {
                                        attrValuePriorities.get(attr).put(value, prio);
                                        prio++;
                                    } else {
                                        delexAttributeValues.get(attr).add(value);
                                    }
                                }
                            } else {
                                for (String value : attributeValues.get(attr)) {
                                    delexAttributeValues.get(attr).add(value);
                                }
                            }
                        }
                    }
                    boolean change = true;
                    while (change) {
                        change = false;
                        for (String attr1 : attrValuePriorities.keySet()) {
                            for (String value1 : attrValuePriorities.get(attr1).keySet()) {
                                for (String attr2 : attrValuePriorities.keySet()) {
                                    for (String value2 : attrValuePriorities.get(attr2).keySet()) {
                                        if (!value1.equals(value2) && value1.contains(value2)
                                                && attrValuePriorities.get(attr1).get(
                                                        value1) > attrValuePriorities.get(attr2).get(value2)) {
                                            int prio1 = attrValuePriorities.get(attr1).get(value1);
                                            int prio2 = attrValuePriorities.get(attr2).get(value2);
                                            attrValuePriorities.get(attr1).put(value1, prio2);
                                            attrValuePriorities.get(attr2).put(value2, prio1);
                                            change = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    HashMap<String, Integer> xCounts = new HashMap<>();
                    HashMap<String, String> delexMap = new HashMap<>();
                    ref = " " + ref + " ";
                    for (int p = 0; p < prio; p++) {
                        for (String attr : attrValuePriorities.keySet()) {
                            if (!xCounts.containsKey(attr)) {
                                xCounts.put(attr, 0);
                            }
                            for (String value : attrValuePriorities.get(attr).keySet()) {
                                if (attrValuePriorities.get(attr).get(value) == p) {
                                    if (!ref.contains(" " + value + " ") && !value.contains(" and ")
                                            && !value.contains(" or ")) {
                                        /*System.out.println(ref);
                                         System.out.println(attr);
                                         System.out.println(value);
                                         System.out.println(attrValuePriorities);*/
                                    } else if (!ref.contains(" " + value + " ")
                                            && (value.contains(" and ") || value.contains(" or "))) {
                                        String[] values = null;
                                        if (value.contains(" and ")) {
                                            values = value.split(" and ");
                                        } else if (value.contains(" or ")) {
                                            values = value.split(" or ");
                                        }
                                        for (int v = 0; v < values.length; v++) {
                                            if (!ref.contains(" " + values[v] + " ")) {
                                                /*System.out.println(ref);
                                                 System.out.println(attr);
                                                 System.out.println(value);
                                                 System.out.println(values[v]);
                                                 System.out.println(attrValuePriorities);*/
                                            } else {
                                                ref = ref.replace(" " + values[v] + " ", " " + SFX.TOKEN_X
                                                        + attr + "_" + xCounts.get(attr) + " ");
                                                ref = ref.replaceAll("  ", " ");
                                                delexAttributeValues.get(attr)
                                                        .add(SFX.TOKEN_X + attr + "_" + xCounts.get(attr));
                                                delexMap.put(SFX.TOKEN_X + attr + "_" + xCounts.get(attr),
                                                        values[v]);
                                                xCounts.put(attr, xCounts.get(attr) + 1);
                                            }
                                        }
                                    } else {
                                        ref = ref.replace(" " + value + " ",
                                                " " + SFX.TOKEN_X + attr + "_" + xCounts.get(attr) + " ");
                                        ref = ref.replaceAll("  ", " ");
                                        delexAttributeValues.get(attr)
                                                .add(SFX.TOKEN_X + attr + "_" + xCounts.get(attr));
                                        delexMap.put(SFX.TOKEN_X + attr + "_" + xCounts.get(attr), value);
                                        xCounts.put(attr, xCounts.get(attr) + 1);
                                    }
                                }
                            }
                        }
                    }
                    ref = ref.trim();
                    MeaningRepresentation MR = new MeaningRepresentation(predicate, delexAttributeValues,
                            MRstr);
                    MR.setDelexMap(delexMap);

                    ArrayList<String> mentionedValueSequence = new ArrayList<>();
                    ArrayList<String> mentionedAttributeSequence = new ArrayList<>();

                    ArrayList<String> realization = new ArrayList<>();
                    ArrayList<String> alignedRealization = new ArrayList<>();

                    String[] words = ref.replaceAll("([,.?!;:'])", " $1").split(" ");
                    HashMap<String, Integer> attributeXCount = new HashMap<>();
                    for (int w = 0; w < words.length; w++) {
                        String mentionedAttribute = "";
                        if (!words[w].trim().isEmpty()) {
                            int s = words[w].indexOf("[");
                            if (s != -1) {
                                int e = words[w].indexOf("]", s + 1);

                                String mentionedValue = words[w].substring(s, e + 1);
                                words[w] = words[w].replace(mentionedValue, "");
                                if (mentionedValue.contains("+") && !words[w].trim().isEmpty()) {
                                    mentionedAttribute = mentionedValue.substring(1,
                                            mentionedValue.indexOf("+"));

                                    if (MR.getAttributes().containsKey(mentionedAttribute)) {
                                        if (mentionedValueSequence.isEmpty()) {
                                            String v = mentionedValue.substring(1, mentionedValue.length() - 1)
                                                    .replaceAll("\\+", "=");
                                            if (v.endsWith("=X")) {
                                                //v = v.replace("=X", "=@@$$" + a + "$$@@");
                                                int a = 0;
                                                if (!attributeXCount.containsKey(mentionedAttribute)) {
                                                    attributeXCount.put(mentionedAttribute, 1);
                                                } else {
                                                    a = attributeXCount.get(mentionedAttribute);
                                                    attributeXCount.put(mentionedAttribute,
                                                            attributeXCount.get(mentionedAttribute) + 1);
                                                }
                                                v = v.replace("=X", "=x" + a);
                                            }
                                            mentionedValueSequence.add(v.toLowerCase());
                                        } else if (!mentionedValueSequence
                                                .get(mentionedValueSequence.size() - 1)
                                                .equals(mentionedValue)) {
                                            String v = mentionedValue.substring(1, mentionedValue.length() - 1)
                                                    .replaceAll("\\+", "=");
                                            if (v.endsWith("=X")) {
                                                //v = v.replace("=X", "=@@$$" + +a + "$$@@");
                                                int a = 0;
                                                if (!attributeXCount.containsKey(mentionedAttribute)) {
                                                    attributeXCount.put(mentionedAttribute, 1);
                                                } else {
                                                    a = attributeXCount.get(mentionedAttribute);
                                                    attributeXCount.put(mentionedAttribute,
                                                            attributeXCount.get(mentionedAttribute) + 1);
                                                }
                                                v = v.replace("=X", "=x" + a);
                                            }
                                            mentionedValueSequence.add(v.toLowerCase());
                                        }

                                        if (mentionedAttributeSequence.isEmpty()) {
                                            mentionedAttributeSequence.add(mentionedAttribute.toLowerCase());
                                        } else if (!mentionedAttributeSequence
                                                .get(mentionedAttributeSequence.size() - 1)
                                                .equals(mentionedAttribute)) {
                                            mentionedAttributeSequence.add(mentionedAttribute.toLowerCase());
                                        }
                                    }
                                } else if (!words[w].trim().isEmpty()) {
                                    mentionedAttribute = mentionedValue.substring(1,
                                            mentionedValue.length() - 1);

                                    if (!MR.getAttributes().containsKey(mentionedAttribute)) {
                                        mentionedAttribute = "";
                                    }
                                }
                            }
                            if (!words[w].trim().isEmpty()) {
                                if (words[w].trim().equals("thers")) {
                                    realization.add("there");
                                } else {
                                    realization.add(words[w].trim().toLowerCase());
                                }
                            }
                        }
                    }

                    for (String attr : MR.getAttributes().keySet()) {
                        for (String value : MR.getAttributes().get(attr)) {
                            if (attr.equals("name") && value.equals("none")) {
                                mentionedValueSequence.add(0, attr.toLowerCase() + "=" + value.toLowerCase());
                                mentionedAttributeSequence.add(0, attr.toLowerCase());
                            }
                        }
                    }

                    mentionedValueSequence.add(SFX.TOKEN_END);
                    mentionedAttributeSequence.add(SFX.TOKEN_END);
                    if (realization.size() > maxWordRealizationSize) {
                        maxWordRealizationSize = realization.size();
                    }

                    for (String word : realization) {
                        if (word.trim().matches("[,.?!;:']")) {
                            alignedRealization.add(SFX.TOKEN_PUNCT);
                        } else {
                            alignedRealization.add("[]");
                        }
                    }

                    //Calculate alignments
                    HashMap<String, HashMap<String, Double>> alignments = new HashMap<>();
                    for (String attr : MR.getAttributes().keySet()) {
                        /*if (attr.equals("name")
                         || attr.equals("type")
                         || attr.equals("pricerange")
                         || attr.equals("price")
                         || attr.equals("phone")
                         || attr.equals("address")
                         || attr.equals("postcode")
                         || attr.equals("area")
                         || attr.equals("near")
                         || attr.equals("food")
                         || attr.equals("count")
                         || attr.equals("goodformeal")) {*/

                        for (String value : MR.getAttributes().get(attr)) {
                            if (!value.equals("name=none") && !value.startsWith(SFX.TOKEN_X)
                                    && !(value.matches("\"[xX][0-9]+\"") || value.matches("[xX][0-9]+"))) {
                                String valueToCheck = value;
                                if (value.equals("no") || value.equals("yes") || value.equals("yes or no")
                                        || value.equals("none") || value.equals("dont_care")
                                        || value.equals("empty")) {
                                    valueToCheck = attr;
                                    alignments.put(valueToCheck + ":" + value, new HashMap<String, Double>());
                                } else {
                                    alignments.put(valueToCheck, new HashMap<String, Double>());
                                }
                                //For all ngrams
                                for (int n = 1; n < realization.size(); n++) {
                                    //Calculate all alignment similarities
                                    for (int r = 0; r <= realization.size() - n; r++) {
                                        boolean pass = true;
                                        for (int j = 0; j < n; j++) {
                                            if (realization.get(r + j).startsWith(SFX.TOKEN_X)
                                                    || alignedRealization.get(r + j).equals(SFX.TOKEN_PUNCT)
                                                    || StringNLPUtilities.isArticle(realization.get(r + j))
                                                    || realization.get(r + j).equalsIgnoreCase("and")
                                                    || realization.get(r + j).equalsIgnoreCase("or")) {
                                                pass = false;
                                            }
                                        }
                                        if (pass) {
                                            String align = "";
                                            String compare = "";
                                            String backwardCompare = "";
                                            for (int j = 0; j < n; j++) {
                                                align += (r + j) + " ";
                                                compare += realization.get(r + j);
                                                backwardCompare = realization.get(r + j) + backwardCompare;
                                            }
                                            align = align.trim();

                                            Double distance = Levenshtein.getSimilarity(
                                                    valueToCheck.toLowerCase(), compare.toLowerCase(), true,
                                                    false);
                                            Double backwardDistance = Levenshtein.getSimilarity(
                                                    valueToCheck.toLowerCase(), backwardCompare.toLowerCase(),
                                                    true, false);

                                            if (backwardDistance > distance) {
                                                distance = backwardDistance;
                                            }
                                            if (distance > 0.3) {
                                                if (value.equals("no") || value.equals("yes")
                                                        || value.equals("yes or no") || value.equals("none")
                                                        || value.equals("dont_care") || value.equals("empty")) {
                                                    alignments.get(valueToCheck + ":" + value).put(align,
                                                            distance);
                                                } else {
                                                    alignments.get(valueToCheck).put(align, distance);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        /*} else {
                         for (String value : MR.getAttributes().get(attr)) {
                         if (!value.equals("no")
                         && !value.equals("yes")
                         && !value.equals("none")) {
                         System.out.println(attr + " " + value);
                         }
                         }
                         }*/
                    }

                    HashSet<String> toRemove = new HashSet<>();
                    for (String value : alignments.keySet()) {
                        if (alignments.get(value).isEmpty()) {
                            toRemove.add(value);
                        }
                    }
                    for (String value : toRemove) {
                        alignments.remove(value);
                    }

                    while (!alignments.keySet().isEmpty()) {
                        Double max = Double.NEGATIVE_INFINITY;
                        String[] bestAlignment = new String[2];
                        for (String value : alignments.keySet()) {
                            for (String alignment : alignments.get(value).keySet()) {
                                if (alignments.get(value).get(alignment) > max) {
                                    max = alignments.get(value).get(alignment);
                                    bestAlignment[0] = value;
                                    bestAlignment[1] = alignment;
                                }
                            }
                        }

                        ArrayList<String> alignedStr = new ArrayList<>();
                        String[] coords = bestAlignment[1].split(" ");

                        if (coords.length == 1) {
                            alignedStr.add(realization.get(Integer.parseInt(coords[0].trim())));
                        } else {
                            for (int a = Integer.parseInt(coords[0].trim()); a <= Integer
                                    .parseInt(coords[coords.length - 1].trim()); a++) {
                                alignedStr.add(realization.get(a));
                            }
                        }

                        if (!valueAlignments.containsKey(bestAlignment[0])) {
                            valueAlignments.put(bestAlignment[0], new HashMap<ArrayList<String>, Double>());
                        }
                        valueAlignments.get(bestAlignment[0]).put(alignedStr, max);

                        alignments.remove(bestAlignment[0]);
                        for (String value : alignments.keySet()) {
                            HashSet<String> alignmentsToBeRemoved = new HashSet<>();
                            for (String alignment : alignments.get(value).keySet()) {
                                String[] othCoords = alignment.split(" ");
                                if (Integer.parseInt(coords[0].trim()) <= Integer.parseInt(othCoords[0].trim())
                                        && (Integer.parseInt(coords[coords.length - 1].trim()) >= Integer
                                                .parseInt(othCoords[0].trim()))
                                        || (Integer.parseInt(othCoords[0].trim()) <= Integer
                                                .parseInt(coords[0].trim())
                                                && Integer.parseInt(
                                                        othCoords[othCoords.length - 1].trim()) >= Integer
                                                                .parseInt(coords[0].trim()))) {
                                    alignmentsToBeRemoved.add(alignment);
                                }
                            }
                            for (String alignment : alignmentsToBeRemoved) {
                                alignments.get(value).remove(alignment);
                            }
                        }
                        toRemove = new HashSet<>();
                        for (String value : alignments.keySet()) {
                            if (alignments.get(value).isEmpty()) {
                                toRemove.add(value);
                            }
                        }
                        for (String value : toRemove) {
                            alignments.remove(value);
                        }
                    }
                    String previousAttr = "";
                    for (int a = alignedRealization.size() - 1; a >= 0; a--) {
                        if (alignedRealization.get(a).isEmpty() || alignedRealization.get(a).equals("[]")) {
                            if (!previousAttr.isEmpty()) {
                                alignedRealization.set(a, previousAttr);
                            }
                        } else if (!alignedRealization.get(a).equals(SFX.TOKEN_PUNCT)) {
                            previousAttr = alignedRealization.get(a);
                        } else {
                            previousAttr = "";
                        }
                    }
                    previousAttr = "";
                    for (int a = 0; a < alignedRealization.size(); a++) {
                        if (alignedRealization.get(a).isEmpty() || alignedRealization.get(a).equals("[]")) {
                            if (!previousAttr.isEmpty()) {
                                alignedRealization.set(a, previousAttr);
                            }
                        } else if (!alignedRealization.get(a).equals(SFX.TOKEN_PUNCT)) {
                            previousAttr = alignedRealization.get(a);
                        } else {
                            previousAttr = "";
                        }
                    }

                    //}
                    ArrayList<Action> realizationActions = new ArrayList<>();
                    for (int r = 0; r < realization.size(); r++) {
                        realizationActions.add(new Action(realization.get(r), alignedRealization.get(r)));
                    }

                    //boolean existing = false;
                    DatasetInstance DI = new DatasetInstance(MR, mentionedValueSequence,
                            mentionedAttributeSequence, realizationActions);
                    for (DatasetInstance existingDI : datasetInstances.get(predicate)) {
                        //if (existingDI.getMeaningRepresentation().equals(previousAMR)) {
                        //if (existingDI.getMeaningRepresentation().getAttributes().equals(MR.getAttributes())) {
                        if (existingDI.getMeaningRepresentation().getAttributes()
                                .equals(DI.getMeaningRepresentation().getAttributes())) {
                            //existing = true;
                            //existingDI.mergeDatasetInstance(mentionedValueSequence, mentionedAttributeSequence, realizationActions);
                            existingDI.mergeDatasetInstance(DI.getEvalMentionedValueSequences(),
                                    DI.getEvalMentionedAttributeSequences(), DI.getEvalRealizations());
                            DI.mergeDatasetInstance(existingDI.getEvalMentionedValueSequences(),
                                    existingDI.getEvalMentionedAttributeSequences(),
                                    existingDI.getEvalRealizations());
                        }
                    }
                    //if (!existing) {
                    //DatasetInstance DI = new DatasetInstance(MR, mentionedValueSequence, mentionedAttributeSequence, realizationActions);
                    datasetInstances.get(predicate).add(DI);
                    //}
                }
                //}
            }
        }
        /*int dis = 0;
         int slots = 0;
         for (String pred : datasetInstances.keySet()) {
         System.out.println("FOR PREDICATE: " + pred);
         System.out.println("=====");
         for (DatasetInstance di : datasetInstances.get(pred)) {
         System.out.println(di.getMeaningRepresentation().getPredicate());
         System.out.println(di.getMeaningRepresentation().getAttributes());
                
         System.out.println("***********");
         System.out.println("R: " + di.getEvalRealizations());
         System.out.println("=======================");
         dis++;
         slots += di.getMeaningRepresentation().getAttributes().size();
         }
         }
         System.out.println(dis);
         System.out.println((double) slots / (double) dis);*/
    } catch (JSONException ex) {
        ex.printStackTrace();
    }
}

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

@Override
public void didReceivedNotification(int id, final Object... args) {
    if (id == NotificationCenter.messagesDidLoaded) {
        int guid = (Integer) args[10];
        if (guid == classGuid) {
            if (!openAnimationEnded) {
                NotificationCenter.getInstance().setAllowedNotificationsDutingAnimation(new int[] {
                        NotificationCenter.chatInfoDidLoaded, NotificationCenter.dialogsNeedReload,
                        NotificationCenter.closeChats,
                        NotificationCenter.botKeyboardDidLoaded/*, NotificationCenter.botInfoDidLoaded*/ });
            }/*www. j av a2  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) {
        long did = (Long) args[0];
        if (did == dialog_id) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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