导航菜单

页面标题

页面副标题

Plus 12 v10.13.1.1 - PlusUtils.java 源代码

正在查看: Plus 12 v10.13.1.1 应用的 PlusUtils.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package org.telegram.messenger;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ConfigurationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.LocaleSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebStorage;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Toast;
import androidx.collection.LongSparseArray;
import androidx.core.content.FileProvider;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.json.JSONArray;
import org.telegram.db.entity.DialogEntity;
import org.telegram.messenger.MessageObject;
import org.telegram.messenger.NotificationCenter;
import org.telegram.messenger.PlusUtils;
import org.telegram.messenger.translator.BaseTranslationEngine;
import org.telegram.messenger.translator.GoogleWebTranslationEngine;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.RequestDelegate;
import org.telegram.tgnet.SerializedData;
import org.telegram.tgnet.TLObject;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.AlertDialog;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.BottomSheet;
import org.telegram.ui.ActionBar.PlusSettings;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.Cells.ChatMessageCell;
import org.telegram.ui.Cells.CheckBoxCell;
import org.telegram.ui.Cells.RadioColorCell;
import org.telegram.ui.Cells.TextCheckBoxCell;
import org.telegram.ui.ChatActivity;
import org.telegram.ui.Components.AlertsCreator;
import org.telegram.ui.Components.BulletinFactory;
import org.telegram.ui.Components.EditTextBoldCursor;
import org.telegram.ui.Components.EditTextCaption;
import org.telegram.ui.Components.FiltersListBottomSheet;
import org.telegram.ui.Components.FloatingDebug.FloatingDebugController;
import org.telegram.ui.Components.InstantCameraView;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.NumberPicker;
import org.telegram.ui.Components.Premium.LimitReachedBottomSheet;
import org.telegram.ui.Components.ShareAlert;
import org.telegram.ui.Components.TextStyleSpan;
import org.telegram.ui.Components.URLSpanMono;
import org.telegram.ui.Components.URLSpanReplacement;
import org.telegram.ui.Components.URLSpanUserMention;
import org.telegram.ui.Components.voip.VoIPHelper;
import org.telegram.ui.FilterCreateActivity;
import org.telegram.ui.LaunchActivity;
import org.telegram.ui.PasscodeActivity;
import org.telegram.ui.Stories.recorder.DualCameraView;
import org.telegram.ui.ThemePreviewActivity;
import org.telegram.ui.WallpapersListActivity;
import org.telegram.ui.bots.BotBiometry;

public class PlusUtils {
    private static final String EXTRA_REQUEST_ID = "request_id";
    private static final long POSTPONE_TIME_THRESHOLD = 86400000;
    private static final String PREFERENCE_KEY_DOWNLOAD_STATE = "Distribute.download_state";
    private static final String PREFERENCE_KEY_DOWNLOAD_TIME = "Distribute.download_time";
    private static final String PREFERENCE_KEY_POSTPONE_TIME = "Distribute.postpone_time";
    private static final String PREFERENCE_KEY_RELEASE_DETAILS = "Distribute.release_details";
    private static final String PREFERENCE_KEY_REQUEST_ID = "Distribute.request_id";
    private static final String PREFERENCE_KEY_TESTER_APP_UPDATE_SETUP_FAILED_MESSAGE_KEY = "Distribute.tester_app_update_setup_failed_message";
    private static final String PREFERENCE_KEY_UPDATE_SETUP_FAILED_MESSAGE_KEY = "Distribute.update_setup_failed_message";
    private static final String PREFERENCE_KEY_UPDATE_SETUP_FAILED_PACKAGE_HASH_KEY = "Distribute.update_setup_failed_package_hash";
    private static final String PREFERENCE_PREFIX = "Distribute.";
    private static final String SERVICE_NAME = "Distribute";
    private static final String TAG = "PlusUtils";
    private static boolean calculated = false;
    private static boolean clearFiltersPreferences = false;
    private static boolean emoticonsLoaded = false;
    private static boolean isAskForStorageDialogVisible = false;
    private static boolean isUpdateDialogRequired = true;
    private static String lastLangSelection = null;
    public static TLRPC.TL_theme loadingTheme = null;
    public static String loadingThemeFileName = null;

    @SuppressLint({"StaticFieldLeak"})
    private static AlertDialog progressDialog = null;
    public static ArrayList<TLRPC.MessageEntity> reportEntities = null;
    private static TLRPC.TL_messageEntityPre reportEntity = null;
    private static List<String> targetLanguagesArray = null;
    private static List<String> targetLanguagesNamesArray = null;
    private static long totalCacheSize = -1;
    private static long totalDatabaseSize = -1;
    private static JSONArray updateInfo;
    private static String updateUrl;
    private static int versionCode;

    public interface ActionDelegate {
        void onCompleted();
    }

    public interface ActionTextDelegate {
        void onCompleted(String text);
    }

    public interface CacheSizeDelegate {
        void onCompleted(ArrayList<Long> list);
    }

    public interface GetStoragePathsDelegate {
        void onCompleted();
    }

    public enum Style {
        BOLD,
        ITALIC,
        STRIKE,
        UNDERLINE,
        MONO,
        URL,
        MENTION,
        SPOILER,
        REGULAR
    }

    public interface TranslateCallBack {

        public final class CC {
            public static void $default$onChanged(TranslateCallBack translateCallBack, String str) {
            }

            public static void $default$onProviderChanged(TranslateCallBack translateCallBack, int i) {
            }
        }

        void onChanged(String toLang);

        void onProviderChanged(int provider);

        void onSuccess(String translation);
    }

    public interface getThemeDelegate {
        void onCompleted(String attachFileName);

        void onError(String error);
    }

    public static String getFilterEmoticonByFlags(int flags) {
        if ((flags & 33554432) != 0) {
            flags -= 33554432;
        }
        if (flags == 1 || flags == 2 || flags == 3) {
            return "👤";
        }
        if (flags == 4) {
            return "👥";
        }
        if (flags == 8) {
            return "📢";
        }
        if (flags == 16) {
            return "🤖";
        }
        if (flags == 63) {
            return "🔔";
        }
        if (flags == 95) {
            return "✅";
        }
        if (flags == 136) {
            return "📢";
        }
        if (flags == 144) {
            return "🤖";
        }
        if (flags == 191) {
            return "🔔";
        }
        if (flags == 223) {
            return "✅";
        }
        switch (flags) {
            case 129:
            case 130:
            case 131:
                return "👤";
            case 132:
                return "👥";
            default:
                return null;
        }
    }

    public static void lambda$switchToAccount$30(DialogInterface dialogInterface, int i) {
    }

    public static void copyLink(String str) {
        copyLink(str, null);
    }

    public static boolean copyLink(String str, MessageObject messageObject) {
        MessageObject messageObject2;
        if (str.startsWith("video?") && messageObject != null && !messageObject.scheduled) {
            int intValue = str.startsWith("video?") ? Utilities.parseInt((CharSequence) str).intValue() : -1;
            if (!(messageObject.isVideo() || messageObject.isRoundVideo() || messageObject.isVoice() || messageObject.isMusic()) && (messageObject2 = messageObject.replyMessageObject) != null) {
                messageObject = messageObject2;
            }
            long dialogId = messageObject.getDialogId();
            int id = messageObject.getId();
            String str2 = null;
            TLRPC.MessageFwdHeader messageFwdHeader = messageObject.messageOwner.fwd_from;
            if (messageFwdHeader != null) {
                TLRPC.Peer peer = messageFwdHeader.saved_from_peer;
                if (peer != null) {
                    dialogId = MessageObject.getPeerId(peer);
                    id = messageObject.messageOwner.fwd_from.saved_from_msg_id;
                } else {
                    TLRPC.Peer peer2 = messageFwdHeader.from_id;
                    if (peer2 != null) {
                        dialogId = MessageObject.getPeerId(peer2);
                        id = messageObject.messageOwner.fwd_from.channel_post;
                    }
                }
            }
            int i = UserConfig.selectedAccount;
            if (DialogObject.isChatDialog(dialogId)) {
                TLRPC.Chat chat = MessagesController.getInstance(i).getChat(Long.valueOf(-dialogId));
                if (chat != null && chat.username != null) {
                    str2 = "https://t.me/" + chat.username + "/" + id + "?t=" + intValue;
                }
            } else {
                TLRPC.User user = MessagesController.getInstance(i).getUser(Long.valueOf(dialogId));
                if (user != null && user.username != null) {
                    str2 = "https://t.me/" + user.username + "/" + id + "?t=" + intValue;
                }
            }
            if (str2 == null) {
                return false;
            }
            return AndroidUtilities.addToClipboard(str2);
        }
        return AndroidUtilities.addToClipboard(str);
    }

    public static void showToast(final Context context, final String msg) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$showToast$0(context, msg);
            }
        });
    }

    public static void lambda$showToast$0(Context context, String str) {
        if (context != null) {
            Toast.makeText(context, str, 0).show();
        }
    }

    public static void showToast(final String msg) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$showToast$1(msg);
            }
        });
    }

    public static void lambda$showToast$1(String str) {
        try {
            if (ApplicationLoader.applicationContext != null) {
                Toast.makeText(ApplicationLoader.applicationContext, str, 0).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getMethodName(TLObject method) {
        if (method == null) {
            return null;
        }
        String obj = method.toString();
        return obj.substring(obj.indexOf("$") + 4, obj.indexOf("@")).replace("_", ".");
    }

    public static void showErrorToast(TLObject method, String text) {
        if (text.contains("FILE_REFERENCE_EXPIRED") || text.contains("MESSAGE_ID") || text.contains("CHANNEL_INVALID")) {
            return;
        }
        if (getMethodName(method) != null) {
            showToast(getMethodName(method) + ": " + text);
            return;
        }
        showToast(text);
    }

    public static void sendLogs(final Activity parentActivity) {
        if (parentActivity == null) {
            return;
        }
        final AlertDialog alertDialog = new AlertDialog(parentActivity, 3);
        alertDialog.setCanCancel(false);
        alertDialog.show();
        Utilities.globalQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$sendLogs$3(alertDialog, parentActivity);
            }
        });
    }

    public static void lambda$sendLogs$3(final org.telegram.ui.ActionBar.AlertDialog r13, final android.app.Activity r14) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.lambda$sendLogs$3(org.telegram.ui.ActionBar.AlertDialog, android.app.Activity):void");
    }

    public static void lambda$sendLogs$2(AlertDialog alertDialog, boolean[] zArr, Activity activity, File file) {
        Uri fromFile;
        try {
            alertDialog.dismiss();
        } catch (Exception unused) {
        }
        if (zArr[0]) {
            int i = Build.VERSION.SDK_INT;
            if (i >= 24) {
                fromFile = FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file);
            } else {
                fromFile = Uri.fromFile(file);
            }
            Intent intent = new Intent("android.intent.action.SEND");
            if (i >= 24) {
                intent.addFlags(1);
            }
            intent.setType("message/rfc822");
            intent.putExtra("android.intent.extra.EMAIL", BuildConfig.APP_CENTER_HASH);
            intent.putExtra("android.intent.extra.SUBJECT", "Logs from " + LocaleController.getInstance().formatterStats.format(System.currentTimeMillis()));
            intent.putExtra("android.intent.extra.STREAM", fromFile);
            activity.startActivityForResult(Intent.createChooser(intent, "Select email application."), 500);
            return;
        }
        Toast.makeText(activity, LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred), 0).show();
    }

    public static String getDialogName(long did) {
        TLRPC.Chat chat;
        if (did < 0 && (chat = MessagesController.getInstance(UserConfig.selectedAccount).getChat(Long.valueOf(-did))) != null) {
            return chat.title;
        }
        TLRPC.Chat chat2 = MessagesController.getInstance(UserConfig.selectedAccount).getChat(Long.valueOf(did));
        TLRPC.User user = MessagesController.getInstance(UserConfig.selectedAccount).getUser(Long.valueOf(did));
        if (user != null) {
            return UserObject.getUserName(user);
        }
        return chat2 != null ? chat2.title : "NULL";
    }

    public static boolean verifyInstallerId() {
        ArrayList arrayList = new ArrayList(Arrays.asList("com.android.vending", "com.google.android.feedback"));
        String installerPackageName = ApplicationLoader.applicationContext != null ? ApplicationLoader.applicationContext.getPackageManager().getInstallerPackageName(ApplicationLoader.applicationContext.getPackageName()) : null;
        return installerPackageName != null && arrayList.contains(installerPackageName);
    }

    public static AlertDialog showDebugMenu(final BaseFragment fragment) {
        int i;
        String str;
        int i2;
        String str2;
        String str3;
        String str4;
        String str5;
        String str6;
        int i3;
        String str7;
        if (fragment == null || fragment.getParentActivity() == null) {
            return null;
        }
        final int i4 = UserConfig.selectedAccount;
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
        builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu));
        boolean z = ApplicationLoader.applicationContext != null && ApplicationLoader.applicationContext.getResources().getBoolean(R.bool.isTablet);
        CharSequence[] charSequenceArr = new CharSequence[38];
        charSequenceArr[0] = LocaleController.getString("DebugMenuImportContacts", R.string.DebugMenuImportContacts);
        charSequenceArr[1] = LocaleController.getString("DebugMenuReloadContacts", R.string.DebugMenuReloadContacts);
        charSequenceArr[2] = LocaleController.getString("DebugMenuResetContacts", R.string.DebugMenuResetContacts);
        charSequenceArr[3] = LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs);
        if (BuildVars.LOGS_ENABLED) {
            i = R.string.DebugMenuDisableLogs;
            str = "DebugMenuDisableLogs";
        } else {
            i = R.string.DebugMenuEnableLogs;
            str = "DebugMenuEnableLogs";
        }
        charSequenceArr[4] = LocaleController.getString(str, i);
        if (SharedConfig.inappCamera) {
            i2 = R.string.DebugMenuDisableCamera;
            str2 = "DebugMenuDisableCamera";
        } else {
            i2 = R.string.DebugMenuEnableCamera;
            str2 = "DebugMenuEnableCamera";
        }
        charSequenceArr[5] = LocaleController.getString(str2, i2);
        charSequenceArr[6] = LocaleController.getString("DebugMenuClearMediaCache", R.string.DebugMenuClearMediaCache);
        charSequenceArr[7] = LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings);
        charSequenceArr[8] = null;
        charSequenceArr[9] = !verifyInstallerId() ? LocaleController.getString("DebugMenuCheckAppUpdate", R.string.DebugMenuCheckAppUpdate) : null;
        charSequenceArr[10] = LocaleController.getString("DebugMenuReadAllDialogs", R.string.DebugMenuReadAllDialogs);
        charSequenceArr[11] = BuildVars.DEBUG_PRIVATE_VERSION ? SharedConfig.disableVoiceAudioEffects ? "Enable voip audio effects" : "Disable voip audio effects" : null;
        boolean z2 = BuildVars.DEBUG_PRIVATE_VERSION;
        charSequenceArr[12] = z2 ? "Clean app update" : null;
        charSequenceArr[13] = z2 ? "Reset suggestions" : null;
        charSequenceArr[14] = z2 ? LocaleController.getString(R.string.DebugMenuClearWebViewCache) : null;
        int i5 = Build.VERSION.SDK_INT;
        if (i5 >= 19) {
            str3 = LocaleController.getString(SharedConfig.debugWebView ? R.string.DebugMenuDisableWebViewDebug : R.string.DebugMenuEnableWebViewDebug);
        } else {
            str3 = null;
        }
        charSequenceArr[15] = str3;
        String str8 = "Enable tablet mode";
        charSequenceArr[16] = (AndroidUtilities.isTabletInternal() && BuildVars.DEBUG_PRIVATE_VERSION) ? SharedConfig.forceDisableTabletMode ? "Enable tablet mode" : "Disable tablet mode" : null;
        if (BuildVars.DEBUG_PRIVATE_VERSION) {
            str4 = LocaleController.getString(SharedConfig.isFloatingDebugActive ? R.string.FloatingDebugDisable : R.string.FloatingDebugEnable);
        } else {
            str4 = null;
        }
        charSequenceArr[17] = str4;
        boolean z3 = BuildVars.DEBUG_PRIVATE_VERSION;
        charSequenceArr[18] = z3 ? "Force remove premium suggestions" : null;
        charSequenceArr[19] = z3 ? "Share device info" : null;
        charSequenceArr[20] = z3 ? "Force performance class" : null;
        charSequenceArr[21] = (!z3 || InstantCameraView.allowBigSizeCameraDebug()) ? null : !SharedConfig.bigCameraForRound ? "Force big camera for round" : "Disable big camera for round";
        charSequenceArr[22] = LocaleController.getString(DualCameraView.dualAvailableStatic(fragment.getParentActivity()) ? "DebugMenuDualOff" : "DebugMenuDualOn");
        charSequenceArr[23] = BuildVars.DEBUG_VERSION ? SharedConfig.useSurfaceInStories ? "back to TextureView in stories" : "use SurfaceView in stories" : null;
        charSequenceArr[24] = BuildVars.DEBUG_PRIVATE_VERSION ? SharedConfig.photoViewerBlur ? "do not blur in photoviewer" : "blur in photoviewer" : null;
        charSequenceArr[25] = !SharedConfig.payByInvoice ? "Enable Invoice Payment" : "Disable Invoice Payment";
        charSequenceArr[26] = BuildVars.DEBUG_PRIVATE_VERSION ? "Update Attach Bots" : null;
        if (i5 >= 21) {
            str5 = !SharedConfig.useCamera2.booleanValue() ? "Use Camera 2 API" : "Use old Camera 1 API";
        } else {
            str5 = null;
        }
        charSequenceArr[27] = str5;
        charSequenceArr[28] = BuildVars.DEBUG_VERSION ? "Clear bot biometry data" : null;
        charSequenceArr[29] = BuildVars.DEBUG_PRIVATE_VERSION ? "Clear all login tokens" : null;
        charSequenceArr[30] = (!SharedConfig.canBlurChat() || i5 < 31) ? null : SharedConfig.useNewBlur ? "back to cpu blur" : "use new gpu blur";
        charSequenceArr[31] = SharedConfig.drawSnowInChat ? "Hide snow in chat" : "Show snow in chat";
        charSequenceArr[32] = !verifyInstallerId() ? "Enable access to external storage" : null;
        charSequenceArr[33] = LocaleController.getString("ResetFolders", R.string.ResetFolders);
        if (i5 >= 29) {
            str6 = SharedConfig.chatBubbles ? "Disable chat bubbles" : "Enable chat bubbles";
        } else {
            str6 = null;
        }
        charSequenceArr[34] = str6;
        if (!BuildVars.BETA_2 || !z) {
            str8 = null;
        } else if (!PlusSettings.disableTabletMode) {
            str8 = "Disable tablet mode";
        }
        charSequenceArr[35] = str8;
        if (SharedConfig.pauseMusicOnRecord) {
            i3 = R.string.DebugMenuDisablePauseMusic;
            str7 = "DebugMenuDisablePauseMusic";
        } else {
            i3 = R.string.DebugMenuEnablePauseMusic;
            str7 = "DebugMenuEnablePauseMusic";
        }
        charSequenceArr[36] = LocaleController.getString(str7, i3);
        charSequenceArr[37] = BuildVars.DEBUG_VERSION ? "Check beta update from firebase" : null;
        builder.setItems(charSequenceArr, new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i6) {
                PlusUtils.lambda$showDebugMenu$7(i4, fragment, dialogInterface, i6);
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        return builder.create();
    }

    public static void lambda$showDebugMenu$7(final int i, BaseFragment baseFragment, DialogInterface dialogInterface, int i2) {
        long j;
        int i3;
        int i4;
        int i5 = 0;
        if (i2 == 0) {
            UserConfig.getInstance(i).syncContacts = true;
            UserConfig.getInstance(i).saveConfig(false);
            ContactsController.getInstance(i).forceImportContacts();
            return;
        }
        if (i2 == 1) {
            ContactsController.getInstance(i).loadContacts(false, 0L);
            return;
        }
        if (i2 == 2) {
            ContactsController.getInstance(i).resetImportedContacts();
            return;
        }
        if (i2 == 3) {
            MessagesController.getInstance(i).forceResetDialogs();
            return;
        }
        if (i2 == 4) {
            BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED;
            ApplicationLoader.applicationContext.getSharedPreferences("systemConfig", 0).edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit();
            if (BuildVars.LOGS_ENABLED) {
                FileLog.d("app start time = " + ApplicationLoader.startTime);
                try {
                    FileLog.d("buildVersion = " + ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0).versionCode);
                    return;
                } catch (Exception e) {
                    FileLog.e(e);
                    return;
                }
            }
            FileLog.getInstance().stopLogcat();
            return;
        }
        if (i2 == 5) {
            SharedConfig.toggleInappCamera();
            return;
        }
        if (i2 == 6) {
            MessagesStorage.getInstance(i).clearSentMedia();
            return;
        }
        if (i2 == 7) {
            VoIPHelper.showCallDebugSettings(baseFragment.getParentActivity());
            return;
        }
        if (i2 == 8) {
            SharedConfig.toggleRoundCamera16to9();
            return;
        }
        if (i2 == 9) {
            ApplicationLoader.checkForUpdates();
            return;
        }
        if (i2 == 10) {
            MessagesStorage.getInstance(i).readAllDialogs(-1);
            return;
        }
        if (i2 == 11) {
            SharedConfig.toggleDisableVoiceAudioEffects();
            return;
        }
        if (i2 == 12) {
            SharedConfig.pendingAppUpdate = null;
            SharedConfig.saveConfig();
            NotificationCenter.getGlobalInstance().lambda$postNotificationNameOnUIThread$1(NotificationCenter.appUpdateAvailable, new Object[0]);
            return;
        }
        if (i2 == 13) {
            Set set = MessagesController.getInstance(i).pendingSuggestions;
            set.add("VALIDATE_PHONE_NUMBER");
            set.add("VALIDATE_PASSWORD");
            NotificationCenter.getGlobalInstance().lambda$postNotificationNameOnUIThread$1(NotificationCenter.newSuggestionsAvailable, new Object[0]);
            return;
        }
        if (i2 == 14) {
            ApplicationLoader.applicationContext.deleteDatabase("webview.db");
            ApplicationLoader.applicationContext.deleteDatabase("webviewCache.db");
            WebStorage.getInstance().deleteAllData();
            return;
        }
        if (i2 == 15) {
            SharedConfig.toggleDebugWebView();
            Toast.makeText(baseFragment.getParentActivity(), LocaleController.getString(SharedConfig.debugWebView ? R.string.DebugMenuWebViewDebugEnabled : R.string.DebugMenuWebViewDebugDisabled), 0).show();
            return;
        }
        if (i2 == 16) {
            SharedConfig.toggleForceDisableTabletMode();
            Activity findActivity = AndroidUtilities.findActivity(baseFragment.getParentActivity());
            Intent launchIntentForPackage = findActivity.getPackageManager().getLaunchIntentForPackage(findActivity.getPackageName());
            findActivity.finishAffinity();
            findActivity.startActivity(launchIntentForPackage);
            System.exit(0);
            return;
        }
        if (i2 == 17) {
            FloatingDebugController.setActive(baseFragment.getParentActivity(), !FloatingDebugController.isActive());
            return;
        }
        if (i2 == 18) {
            MessagesController.getInstance(i).loadAppConfig();
            TLRPC.TL_help_dismissSuggestion tL_help_dismissSuggestion = new TLRPC.TL_help_dismissSuggestion();
            tL_help_dismissSuggestion.suggestion = "VALIDATE_PHONE_NUMBER";
            tL_help_dismissSuggestion.peer = new TLRPC.TL_inputPeerEmpty();
            ConnectionsManager.getInstance(i).sendRequest(tL_help_dismissSuggestion, new RequestDelegate() {
                @Override
                public final void run(TLObject tLObject, TLRPC.TL_error tL_error) {
                    PlusUtils.lambda$showDebugMenu$5(i, tLObject, tL_error);
                }
            });
            return;
        }
        if (i2 != 19) {
            if (i2 == 20) {
                AlertDialog.Builder builder = new AlertDialog.Builder(baseFragment.getParentActivity());
                builder.setTitle("Force performance class");
                int devicePerformanceClass = SharedConfig.getDevicePerformanceClass();
                final int measureDevicePerformanceClass = SharedConfig.measureDevicePerformanceClass();
                CharSequence[] charSequenceArr = new CharSequence[3];
                StringBuilder sb = new StringBuilder();
                sb.append(devicePerformanceClass == 2 ? "**HIGH**" : "HIGH");
                sb.append(measureDevicePerformanceClass == 2 ? " (measured)" : BuildConfig.APP_CENTER_HASH);
                charSequenceArr[0] = AndroidUtilities.replaceTags(sb.toString());
                StringBuilder sb2 = new StringBuilder();
                sb2.append(devicePerformanceClass == 1 ? "**AVERAGE**" : "AVERAGE");
                sb2.append(measureDevicePerformanceClass == 1 ? " (measured)" : BuildConfig.APP_CENTER_HASH);
                charSequenceArr[1] = AndroidUtilities.replaceTags(sb2.toString());
                StringBuilder sb3 = new StringBuilder();
                sb3.append(devicePerformanceClass == 0 ? "**LOW**" : "LOW");
                sb3.append(measureDevicePerformanceClass != 0 ? BuildConfig.APP_CENTER_HASH : " (measured)");
                charSequenceArr[2] = AndroidUtilities.replaceTags(sb3.toString());
                builder.setItems(charSequenceArr, new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface2, int i6) {
                        PlusUtils.lambda$showDebugMenu$6(measureDevicePerformanceClass, dialogInterface2, i6);
                    }
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
                builder.show();
                return;
            }
            if (i2 == 21) {
                SharedConfig.toggleRoundCamera();
                return;
            }
            if (i2 == 22) {
                boolean dualAvailableStatic = DualCameraView.dualAvailableStatic(baseFragment.getContext());
                MessagesController.getGlobalMainSettings().edit().putBoolean("dual_available", !dualAvailableStatic).apply();
                try {
                    Toast.makeText(baseFragment.getParentActivity(), LocaleController.getString(!dualAvailableStatic ? R.string.DebugMenuDualOnToast : R.string.DebugMenuDualOffToast), 0).show();
                    return;
                } catch (Exception unused) {
                    return;
                }
            }
            if (i2 == 23) {
                SharedConfig.toggleSurfaceInStories();
                while (i5 < baseFragment.getParentLayout().getFragmentStack().size()) {
                    ((BaseFragment) baseFragment.getParentLayout().getFragmentStack().get(i5)).clearStoryViewers();
                    i5++;
                }
                return;
            }
            if (i2 == 24) {
                SharedConfig.togglePhotoViewerBlur();
                return;
            }
            if (i2 == 25) {
                SharedConfig.togglePaymentByInvoice();
                return;
            }
            if (i2 == 26) {
                MediaDataController.getInstance(i).loadAttachMenuBots(false, true);
                return;
            }
            if (i2 == 27) {
                SharedConfig.toggleUseCamera2();
                return;
            }
            if (i2 == 28) {
                BotBiometry.clear();
                return;
            }
            if (i2 == 29) {
                AuthTokensHelper.clearLogInTokens();
                return;
            }
            if (i2 == 30) {
                SharedConfig.toggleUseNewBlur();
                return;
            }
            if (i2 == 31) {
                SharedConfig.toggleDrawSnowInChat();
                return;
            }
            if (i2 == 32) {
                askForExternalStoragePermission(baseFragment.getParentActivity(), true);
                return;
            }
            if (i2 == 33) {
                resetFolders(baseFragment, true);
                return;
            }
            if (i2 == 34) {
                SharedConfig.toggleChatBubbles();
                return;
            }
            if (i2 == 35) {
                try {
                    PlusSettings.disableTabletMode = !PlusSettings.disableTabletMode;
                    ApplicationLoader.applicationContext.getSharedPreferences("plusconfig", 0).edit().putBoolean("disableTabletMode", PlusSettings.disableTabletMode).apply();
                    baseFragment.getParentLayout().rebuildAllFragmentViews(true, true);
                    return;
                } catch (Exception e2) {
                    e2.printStackTrace();
                    return;
                }
            }
            if (i2 == 36) {
                SharedConfig.togglePauseMusicOnRecord();
                return;
            } else {
                if (i2 == 37) {
                    ApplicationLoader.checkFirebaseAppDistribution(true);
                    return;
                }
                return;
            }
        }
        int i6 = ConnectionsManager.CPU_COUNT;
        int memoryClass = ((ActivityManager) ApplicationLoader.applicationContext.getSystemService("activity")).getMemoryClass();
        StringBuilder sb4 = new StringBuilder();
        long j2 = 0;
        long j3 = 0;
        long j4 = 0;
        long j5 = 0;
        long j6 = 0;
        long j7 = 0;
        long j8 = 0;
        long j9 = 0;
        while (i5 < i6) {
            Long sysInfoLong = AndroidUtilities.getSysInfoLong("/sys/devices/system/cpu/cpu" + i5 + "/cpufreq/cpuinfo_min_freq");
            Long sysInfoLong2 = AndroidUtilities.getSysInfoLong("/sys/devices/system/cpu/cpu" + i5 + "/cpufreq/cpuinfo_cur_freq");
            StringBuilder sb5 = new StringBuilder();
            sb5.append("/sys/devices/system/cpu/cpu");
            sb5.append(i5);
            int i7 = i6;
            sb5.append("/cpufreq/cpuinfo_max_freq");
            Long sysInfoLong3 = AndroidUtilities.getSysInfoLong(sb5.toString());
            Long sysInfoLong4 = AndroidUtilities.getSysInfoLong("/sys/devices/system/cpu/cpu" + i5 + "/cpu_capacity");
            sb4.append("#");
            sb4.append(i5);
            sb4.append(" ");
            if (sysInfoLong != null) {
                i4 = memoryClass;
                sb4.append("min=");
                i3 = i5;
                sb4.append(sysInfoLong.longValue() / 1000);
                sb4.append(" ");
                j2 += sysInfoLong.longValue() / 1000;
                j3++;
            } else {
                i3 = i5;
                i4 = memoryClass;
            }
            if (sysInfoLong2 != null) {
                sb4.append("cur=");
                sb4.append(sysInfoLong2.longValue() / 1000);
                sb4.append(" ");
                j4 += sysInfoLong2.longValue() / 1000;
                j5++;
            }
            if (sysInfoLong3 != null) {
                sb4.append("max=");
                sb4.append(sysInfoLong3.longValue() / 1000);
                sb4.append(" ");
                j6 += sysInfoLong3.longValue() / 1000;
                j7++;
            }
            if (sysInfoLong4 != null) {
                sb4.append("cpc=");
                sb4.append(sysInfoLong4);
                sb4.append(" ");
                j8 += sysInfoLong4.longValue();
                j9++;
            }
            sb4.append("\n");
            i5 = i3 + 1;
            i6 = i7;
            memoryClass = i4;
        }
        int i8 = i6;
        int i9 = memoryClass;
        StringBuilder sb6 = new StringBuilder();
        sb6.append(Build.MANUFACTURER);
        sb6.append(", ");
        sb6.append(Build.MODEL);
        sb6.append(" (");
        sb6.append(Build.PRODUCT);
        sb6.append(", ");
        sb6.append(Build.DEVICE);
        sb6.append(") ");
        sb6.append(" (android ");
        int i10 = Build.VERSION.SDK_INT;
        sb6.append(i10);
        sb6.append(")\n");
        if (i10 >= 31) {
            sb6.append("SoC: ");
            sb6.append(Build.SOC_MANUFACTURER);
            sb6.append(", ");
            sb6.append(Build.SOC_MODEL);
            sb6.append("\n");
        }
        String sysInfoString = AndroidUtilities.getSysInfoString("/sys/kernel/gpu/gpu_model");
        if (sysInfoString != null) {
            sb6.append("GPU: ");
            sb6.append(sysInfoString);
            Long sysInfoLong5 = AndroidUtilities.getSysInfoLong("/sys/kernel/gpu/gpu_min_clock");
            Long sysInfoLong6 = AndroidUtilities.getSysInfoLong("/sys/kernel/gpu/gpu_mm_min_clock");
            Long sysInfoLong7 = AndroidUtilities.getSysInfoLong("/sys/kernel/gpu/gpu_max_clock");
            if (sysInfoLong5 != null) {
                sb6.append(", min=");
                j = j4;
                sb6.append(sysInfoLong5.longValue() / 1000);
            } else {
                j = j4;
            }
            if (sysInfoLong6 != null) {
                sb6.append(", mmin=");
                sb6.append(sysInfoLong6.longValue() / 1000);
            }
            if (sysInfoLong7 != null) {
                sb6.append(", max=");
                sb6.append(sysInfoLong7.longValue() / 1000);
            }
            sb6.append("\n");
        } else {
            j = j4;
        }
        ConfigurationInfo deviceConfigurationInfo = ((ActivityManager) ApplicationLoader.applicationContext.getSystemService("activity")).getDeviceConfigurationInfo();
        sb6.append("GLES Version: ");
        sb6.append(deviceConfigurationInfo.getGlEsVersion());
        sb6.append("\n");
        sb6.append("Memory: class=");
        sb6.append(AndroidUtilities.formatFileSize(i9 * 1024 * 1024));
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ((ActivityManager) ApplicationLoader.applicationContext.getSystemService("activity")).getMemoryInfo(memoryInfo);
        sb6.append(", total=");
        sb6.append(AndroidUtilities.formatFileSize(memoryInfo.totalMem));
        sb6.append(", avail=");
        sb6.append(AndroidUtilities.formatFileSize(memoryInfo.availMem));
        sb6.append(", low?=");
        sb6.append(memoryInfo.lowMemory);
        sb6.append(" (threshold=");
        sb6.append(AndroidUtilities.formatFileSize(memoryInfo.threshold));
        sb6.append(")");
        sb6.append("\n");
        sb6.append("Current class: ");
        sb6.append(SharedConfig.performanceClassName(SharedConfig.getDevicePerformanceClass()));
        sb6.append(", measured: ");
        sb6.append(SharedConfig.performanceClassName(SharedConfig.measureDevicePerformanceClass()));
        if (i10 >= 31) {
            sb6.append(", suggest=");
            sb6.append(Build.VERSION.MEDIA_PERFORMANCE_CLASS);
        }
        sb6.append("\n");
        sb6.append(i8);
        sb6.append(" CPUs");
        if (j3 > 0) {
            sb6.append(", avgMinFreq=");
            sb6.append(j2 / j3);
        }
        if (j5 > 0) {
            sb6.append(", avgCurFreq=");
            sb6.append(j / j5);
        }
        if (j7 > 0) {
            sb6.append(", avgMaxFreq=");
            sb6.append(j6 / j7);
        }
        if (j9 > 0) {
            sb6.append(", avgCapacity=");
            sb6.append(j8 / j9);
        }
        sb6.append("\n");
        sb6.append((CharSequence) sb4);
        baseFragment.showDialog(new AnonymousClass2(baseFragment.getParentActivity(), null, sb6.toString(), false, null, false, baseFragment));
    }

    public static void lambda$showDebugMenu$5(final int i, TLObject tLObject, TLRPC.TL_error tL_error) {
        TLRPC.TL_help_dismissSuggestion tL_help_dismissSuggestion = new TLRPC.TL_help_dismissSuggestion();
        tL_help_dismissSuggestion.suggestion = "VALIDATE_PASSWORD";
        tL_help_dismissSuggestion.peer = new TLRPC.TL_inputPeerEmpty();
        ConnectionsManager.getInstance(i).sendRequest(tL_help_dismissSuggestion, new RequestDelegate() {
            @Override
            public final void run(TLObject tLObject2, TLRPC.TL_error tL_error2) {
                PlusUtils.lambda$showDebugMenu$4(i, tLObject2, tL_error2);
            }
        });
    }

    public static void lambda$showDebugMenu$4(int i, TLObject tLObject, TLRPC.TL_error tL_error) {
        MessagesController.getInstance(i).loadAppConfig();
    }

    public class AnonymousClass2 extends ShareAlert {
        public final BaseFragment val$fragment;

        public AnonymousClass2(final Context context, ArrayList messages, final String text, boolean channel, final String copyLink, boolean fullScreen, final BaseFragment val$fragment) {
            super(context, messages, text, channel, copyLink, fullScreen);
            this.val$fragment = val$fragment;
        }

        @Override
        public void onSend(final LongSparseArray<TLRPC.Dialog> dids, final int count, TLRPC.TL_forumTopic topic) {
            final BaseFragment baseFragment = this.val$fragment;
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    PlusUtils.AnonymousClass2.this.lambda$onSend$0(baseFragment, dids, count);
                }
            }, 250L);
        }

        public void lambda$onSend$0(BaseFragment baseFragment, LongSparseArray longSparseArray, int i) {
            BulletinFactory.createInviteSentBulletin(baseFragment.getParentActivity(), baseFragment.getLayoutContainer(), longSparseArray.size(), longSparseArray.size() == 1 ? ((TLRPC.Dialog) longSparseArray.valueAt(0)).id : 0L, i, getThemedColor(Theme.key_undo_background), getThemedColor(Theme.key_undo_infoColor)).show();
        }
    }

    public static void lambda$showDebugMenu$6(int i, DialogInterface dialogInterface, int i2) {
        int i3 = 2 - i2;
        if (i3 == i) {
            SharedConfig.overrideDevicePerformanceClass(-1);
        } else {
            SharedConfig.overrideDevicePerformanceClass(i3);
        }
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        try {
            return context.getPackageManager().getLaunchIntentForPackage(packageName) != null;
        } catch (Exception unused) {
            return false;
        }
    }

    public static AlertDialog showReportDetailsDialog(final BaseFragment fragment, final MessageObject repply_to_msg) {
        if (fragment == null || fragment.getParentActivity() == null) {
            return null;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
        builder.setTitle(LocaleController.getString("SendPlusDetails", R.string.SendPlusDetails));
        final String[] strArr = {getReportDetails()};
        builder.setMessage(strArr[0] + "\n\n" + LocaleController.getString("Loading", R.string.Loading));
        builder.setPositiveButton(LocaleController.getString("Send", R.string.Send), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (fragment instanceof ChatActivity) {
                    MessagesController.getInstance(UserConfig.selectedAccount).getSendMessagesHelper().sendMessage(strArr[0], fragment.getDialogId(), repply_to_msg, (MessageObject) null, (TLRPC.WebPage) null, false, PlusUtils.reportEntities, (TLRPC.ReplyMarkup) null, (HashMap) null, true, 0, (MessageObject.SendAnimationData) null, false);
                }
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        builder.setNeutralButton(LocaleController.getString("Copy", R.string.Copy), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ((ClipboardManager) ApplicationLoader.applicationContext.getSystemService("clipboard")).setPrimaryClip(ClipData.newPlainText("label", strArr[0]));
                Toast.makeText(fragment.getParentActivity(), LocaleController.formatString("Copied", R.string.Copied, new Object[]{strArr[0]}), 0).show();
            }
        });
        AlertDialog create = builder.create();
        getCacheSize(new AnonymousClass5(strArr, create));
        return create;
    }

    public class AnonymousClass5 implements CacheSizeDelegate {
        public final AlertDialog val$dialog;
        public final String[] val$report;

        public AnonymousClass5(final String[] val$report, final AlertDialog val$dialog) {
            this.val$report = val$report;
            this.val$dialog = val$dialog;
        }

        @Override
        public void onCompleted(ArrayList<Long> sizes) {
            if (PlusUtils.totalCacheSize > 0 || PlusUtils.totalDatabaseSize > 0) {
                String str = (PlusUtils.getReportDetails() + "\nCache: " + PlusUtils.formatFileSize(PlusUtils.totalCacheSize)) + "\nDatabase: " + PlusUtils.formatFileSize(PlusUtils.totalDatabaseSize);
                long longValue = sizes.get(sizes.size() - 2).longValue();
                sizes.get(sizes.size() - 3).longValue();
                String str2 = str + "\nFree: " + PlusUtils.formatFileSize(longValue);
                final String[] strArr = this.val$report;
                strArr[0] = str2;
                try {
                    final AlertDialog alertDialog = this.val$dialog;
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public final void run() {
                            PlusUtils.AnonymousClass5.lambda$onCompleted$0(alertDialog, strArr);
                        }
                    });
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        }

        public static void lambda$onCompleted$0(AlertDialog alertDialog, String[] strArr) {
            if (alertDialog != null) {
                alertDialog.setMessage(strArr[0]);
            }
        }
    }

    public static String formatFileSize(long size) {
        return formatFileSize(size, Locale.US);
    }

    public static String formatFileSize(long size, Locale locale) {
        return size == 0 ? String.format(locale, "%d KB", 0) : size < 1024 ? String.format(locale, "%d B", Long.valueOf(size)) : size < 1048576 ? String.format(locale, "%.1f KB", Float.valueOf(size / 1024.0f)) : size < 1048576000 ? String.format(locale, "%.1f MB", Float.valueOf((size / 1024.0f) / 1024.0f)) : String.format(locale, "%.2f GB", Float.valueOf(((int) ((size / 1024) / 1024)) / 1000.0f));
    }

    public static AlertDialog showSwitchAccountDialog(final BaseFragment fragment) {
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
        builder.setTitle(LocaleController.getString(R.string.AppName));
        builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("AccountSwitch", R.string.AccountSwitch)));
        builder.setPositiveButton(LocaleController.getString(R.string.Close), (DialogInterface.OnClickListener) null);
        builder.setNegativeButton(LocaleController.getString(R.string.Open), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                PlusUtils.lambda$showSwitchAccountDialog$8(fragment, dialogInterface, i);
            }
        });
        return builder.create();
    }

    public static void lambda$showSwitchAccountDialog$8(BaseFragment baseFragment, DialogInterface dialogInterface, int i) {
        try {
            Intent intent = new Intent("org.telegram.passport.AUTHORIZE");
            intent.putExtra("remove", true);
            baseFragment.getParentActivity().startActivity(intent);
        } catch (Exception unused) {
        }
    }

    public static String getReportDetails() {
        reportEntities = new ArrayList<>();
        TLRPC.TL_messageEntityPre tL_messageEntityPre = new TLRPC.TL_messageEntityPre();
        reportEntity = tL_messageEntityPre;
        tL_messageEntityPre.offset = 0;
        String str = (BuildConfig.APP_CENTER_HASH + getVersionInfo()) + '\n' + Build.BRAND + " " + Build.MODEL + " android " + Build.VERSION.RELEASE;
        String str2 = Build.DISPLAY;
        if (!TextUtils.isEmpty(str2)) {
            str = str + "\nROM: " + str2;
        }
        if (PlusSettings.getStorage() > 0) {
            str = str + "\nSD storage";
        }
        if (PlusSettings.getKeepOriginalFilename()) {
            str = str + "\nKeep original name: true";
        }
        if (MessagesStorage.getInstance(UserConfig.selectedAccount).foldersError) {
            str = str + "\nFolders error: true";
        }
        if (UserConfig.getActivatedAccountsCount() > 1) {
            str = str + "\nAccounts: " + UserConfig.getActivatedAccountsCount();
        }
        int i = MessagesController.getInstance(UserConfig.selectedAccount).remoteFoldersCount - 1;
        int size = (MessagesController.getInstance(UserConfig.selectedAccount).dialogFilters.size() - 1) - i;
        if (size > 0) {
            str = str + "\nFolders: Cloud " + i + " Local " + size;
        }
        int devicePerformanceClass = SharedConfig.getDevicePerformanceClass();
        StringBuilder sb = new StringBuilder();
        sb.append(str);
        sb.append("\nPerformance: ");
        sb.append(devicePerformanceClass == 0 ? "LOW" : devicePerformanceClass == 1 ? "AVERAGE" : "HIGH");
        String sb2 = sb.toString();
        reportEntity.length = sb2.length() + 50;
        reportEntities.add(reportEntity);
        return sb2;
    }

    public static void applyMonoStyle(int start, String text) {
        int length = text.length();
        TextStyleSpan.TextStyleRun textStyleRun = new TextStyleSpan.TextStyleRun();
        textStyleRun.flags |= 4;
        MediaDataController.addStyleToText(new TextStyleSpan(textStyleRun), start, length, new SpannableString(text), true);
    }

    private static java.lang.String getVersionInfo() {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.getVersionInfo():java.lang.String");
    }

    public static String addQualityToId(String id) {
        if (TextUtils.isEmpty(id)) {
            return id;
        }
        String str = Theme.plusPhotoQuality + BuildConfig.APP_CENTER_HASH;
        return id.substring(0, id.length() - str.length()) + str;
    }

    public static void getCacheSize(final CacheSizeDelegate delegate) {
        final ArrayList arrayList = new ArrayList();
        Utilities.globalQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$getCacheSize$9(arrayList, delegate);
            }
        });
    }

    public static void lambda$getCacheSize$9(ArrayList arrayList, CacheSizeDelegate cacheSizeDelegate) {
        int i;
        int i2;
        long j;
        long j2;
        File file;
        long blockSize;
        long availableBlocks;
        long blockCount;
        totalCacheSize = -1L;
        totalDatabaseSize = -1L;
        calculated = false;
        arrayList.add(-1L);
        long directorySize = getDirectorySize(FileLoader.checkDirectory(4), 0);
        arrayList.add(Long.valueOf(directorySize));
        long directorySize2 = getDirectorySize(FileLoader.checkDirectory(0), 0);
        arrayList.add(Long.valueOf(directorySize2));
        long directorySize3 = getDirectorySize(FileLoader.checkDirectory(2), 0);
        arrayList.add(Long.valueOf(directorySize3));
        long directorySize4 = getDirectorySize(FileLoader.checkDirectory(3), 1);
        arrayList.add(Long.valueOf(directorySize4));
        long directorySize5 = getDirectorySize(FileLoader.checkDirectory(3), 2);
        arrayList.add(Long.valueOf(directorySize5));
        long directorySize6 = getDirectorySize(new File(FileLoader.checkDirectory(4), "acache"), 0);
        arrayList.add(Long.valueOf(directorySize6));
        long directorySize7 = getDirectorySize(FileLoader.checkDirectory(7), 0);
        arrayList.add(Long.valueOf(directorySize7));
        File externalFilesDir = ApplicationLoader.applicationContext.getExternalFilesDir(null);
        if (externalFilesDir != null) {
            j = getDirectorySize(new File(externalFilesDir.getAbsolutePath() + "/logs"), 0);
            arrayList.add(Long.valueOf(j));
            if (j <= 262144) {
                j = 0;
            }
            i = 0;
            long directorySize8 = getDirectorySize(new File(externalFilesDir.getAbsolutePath() + "/Download"), 0);
            arrayList.add(Long.valueOf(directorySize8));
            j2 = directorySize8;
            i2 = 1;
        } else {
            i = 0;
            i2 = 1;
            j = -1;
            j2 = -1;
        }
        long directorySize9 = getDirectorySize(FileLoader.checkDirectory(i2), i);
        arrayList.add(Long.valueOf(directorySize9));
        long j3 = directorySize + directorySize3 + directorySize9 + directorySize2 + directorySize4 + directorySize5 + directorySize6 + directorySize7 + j + j2;
        totalCacheSize = j3;
        arrayList.set(0, Long.valueOf(j3));
        if (Build.VERSION.SDK_INT >= 19) {
            ArrayList rootDirs = AndroidUtilities.getRootDirs();
            file = (File) rootDirs.get(0);
            file.getAbsolutePath();
            if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
                int size = rootDirs.size();
                for (int i3 = 0; i3 < size; i3++) {
                    File file2 = (File) rootDirs.get(i3);
                    if (file2.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
                        file = file2;
                        break;
                    }
                }
            }
        } else {
            file = new File(SharedConfig.storageCacheDir);
        }
        try {
            StatFs statFs = new StatFs(file.getPath());
            int i4 = Build.VERSION.SDK_INT;
            if (i4 >= 18) {
                blockSize = statFs.getBlockSizeLong();
            } else {
                blockSize = statFs.getBlockSize();
            }
            if (i4 >= 18) {
                availableBlocks = statFs.getAvailableBlocksLong();
            } else {
                availableBlocks = statFs.getAvailableBlocks();
            }
            if (i4 >= 18) {
                blockCount = statFs.getBlockCountLong();
            } else {
                blockCount = statFs.getBlockCount();
            }
            arrayList.add(Long.valueOf(blockCount * blockSize));
            arrayList.add(Long.valueOf(availableBlocks * blockSize));
        } catch (Exception e) {
            FileLog.e(e);
        }
        long databaseSize = MessagesStorage.getInstance(UserConfig.selectedAccount).getDatabaseSize();
        totalDatabaseSize = databaseSize;
        arrayList.add(Long.valueOf(databaseSize));
        if (cacheSizeDelegate != null) {
            cacheSizeDelegate.onCompleted(arrayList);
        }
        calculated = true;
    }

    public static void exportTheme(android.app.Activity r4, org.telegram.ui.ActionBar.Theme.ThemeInfo r5) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.exportTheme(android.app.Activity, org.telegram.ui.ActionBar.Theme$ThemeInfo):void");
    }

    public static void getTheme(final Activity activity, final String theme, final getThemeDelegate delegate) {
        final int i = UserConfig.selectedAccount;
        final String[] strArr = new String[1];
        final TLRPC.TL_wallPaper[] tL_wallPaperArr = new TLRPC.TL_wallPaper[1];
        final Theme.ThemeInfo[] themeInfoArr = new Theme.ThemeInfo[1];
        final boolean[] zArr = new boolean[1];
        final AlertDialog[] alertDialogArr = new AlertDialog[1];
        final AlertDialog alertDialog = new AlertDialog(activity, 3);
        new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$getTheme$10(strArr, tL_wallPaperArr, themeInfoArr, alertDialogArr);
            }
        };
        TLRPC.TL_account_getTheme tL_account_getTheme = new TLRPC.TL_account_getTheme();
        tL_account_getTheme.format = "android";
        TLRPC.TL_inputThemeSlug tL_inputThemeSlug = new TLRPC.TL_inputThemeSlug();
        tL_inputThemeSlug.slug = theme;
        tL_account_getTheme.theme = tL_inputThemeSlug;
        ConnectionsManager.getInstance(i).sendRequest(tL_account_getTheme, new RequestDelegate() {
            @Override
            public final void run(TLObject tLObject, TLRPC.TL_error tL_error) {
                PlusUtils.lambda$getTheme$14(i, alertDialogArr, alertDialog, zArr, tL_wallPaperArr, strArr, delegate, activity, theme, tLObject, tL_error);
            }
        });
    }

    public static void lambda$getTheme$10(String[] strArr, TLRPC.TL_wallPaper[] tL_wallPaperArr, Theme.ThemeInfo[] themeInfoArr, AlertDialog[] alertDialogArr) {
        loadingThemeFileName = null;
        strArr[0] = null;
        tL_wallPaperArr[0] = null;
        themeInfoArr[0] = null;
        alertDialogArr[0] = null;
        loadingTheme = null;
    }

    public static void lambda$getTheme$14(final int i, final AlertDialog[] alertDialogArr, final AlertDialog alertDialog, final boolean[] zArr, final TLRPC.TL_wallPaper[] tL_wallPaperArr, final String[] strArr, final getThemeDelegate getthemedelegate, final Activity activity, final String str, final TLObject tLObject, final TLRPC.TL_error tL_error) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$getTheme$13(tLObject, i, alertDialogArr, alertDialog, zArr, tL_wallPaperArr, strArr, getthemedelegate, activity, str, tL_error);
            }
        });
    }

    public static void lambda$getTheme$13(org.telegram.tgnet.TLObject r14, int r15, org.telegram.ui.ActionBar.AlertDialog[] r16, org.telegram.ui.ActionBar.AlertDialog r17, boolean[] r18, org.telegram.tgnet.TLRPC.TL_wallPaper[] r19, java.lang.String[] r20, final org.telegram.messenger.PlusUtils.getThemeDelegate r21, final android.app.Activity r22, final java.lang.String r23, org.telegram.tgnet.TLRPC.TL_error r24) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.lambda$getTheme$13(org.telegram.tgnet.TLObject, int, org.telegram.ui.ActionBar.AlertDialog[], org.telegram.ui.ActionBar.AlertDialog, boolean[], org.telegram.tgnet.TLRPC$TL_wallPaper[], java.lang.String[], org.telegram.messenger.PlusUtils$getThemeDelegate, android.app.Activity, java.lang.String, org.telegram.tgnet.TLRPC$TL_error):void");
    }

    public static void lambda$getTheme$11(File file, Activity activity, String str, getThemeDelegate getthemedelegate) {
        if (file.exists()) {
            shareTheme(activity, str);
        } else if (getthemedelegate != null) {
            getthemedelegate.onError("THEME DOESN'T EXIST");
        }
    }

    public static void lambda$getTheme$12(File file, Activity activity, String str, getThemeDelegate getthemedelegate) {
        if (file.exists()) {
            shareTheme(activity, str);
        } else if (getthemedelegate != null) {
            getthemedelegate.onError("THEME DOESN'T EXIST");
        }
    }

    public static void getWallpaper(Activity activity, final TLRPC.TL_wallPaper wallPaper, getThemeDelegate delegate) {
        int i = UserConfig.selectedAccount;
        TLRPC.TL_account_getWallPaper tL_account_getWallPaper = new TLRPC.TL_account_getWallPaper();
        TLRPC.TL_inputWallPaper tL_inputWallPaper = new TLRPC.TL_inputWallPaper();
        tL_inputWallPaper.id = wallPaper.id;
        tL_inputWallPaper.access_hash = wallPaper.access_hash;
        tL_account_getWallPaper.wallpaper = tL_inputWallPaper;
        boolean z = false;
        if (TextUtils.isEmpty(wallPaper.slug)) {
            try {
                TLRPC.WallPaperSettings wallPaperSettings = wallPaper.settings;
                new ThemePreviewActivity(new WallpapersListActivity.ColorWallpaper("c", wallPaperSettings.background_color, wallPaperSettings.second_background_color, AndroidUtilities.getWallpaperRotation(wallPaperSettings.rotation, false)), (Bitmap) null);
                z = true;
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
        if (z) {
            return;
        }
        TLRPC.TL_inputWallPaperSlug tL_inputWallPaperSlug = new TLRPC.TL_inputWallPaperSlug();
        tL_inputWallPaperSlug.slug = wallPaper.slug;
        tL_account_getWallPaper.wallpaper = tL_inputWallPaperSlug;
        ConnectionsManager.getInstance(i).sendRequest(tL_account_getWallPaper, new RequestDelegate() {
            @Override
            public final void run(TLObject tLObject, TLRPC.TL_error tL_error) {
                PlusUtils.lambda$getWallpaper$16(TLRPC.TL_wallPaper.this, tLObject, tL_error);
            }
        });
    }

    public static void lambda$getWallpaper$16(final TLRPC.TL_wallPaper tL_wallPaper, final TLObject tLObject, TLRPC.TL_error tL_error) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$getWallpaper$15(tLObject, tL_wallPaper);
            }
        });
    }

    public static void lambda$getWallpaper$15(TLObject tLObject, TLRPC.TL_wallPaper tL_wallPaper) {
        try {
            progressDialog.dismiss();
        } catch (Exception e) {
            FileLog.e(e);
        }
        if (tLObject instanceof TLRPC.TL_wallPaper) {
            TLRPC.TL_wallPaper tL_wallPaper2 = (TLRPC.TL_wallPaper) tLObject;
            if (tL_wallPaper2.pattern) {
                String str = tL_wallPaper2.slug;
                TLRPC.WallPaperSettings wallPaperSettings = tL_wallPaper.settings;
                TLRPC.TL_wallPaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(str, wallPaperSettings.background_color, wallPaperSettings.second_background_color, AndroidUtilities.getWallpaperRotation(wallPaperSettings.rotation, false));
                ((WallpapersListActivity.ColorWallpaper) colorWallpaper).pattern = tL_wallPaper2;
                tL_wallPaper2 = colorWallpaper;
            }
            ThemePreviewActivity themePreviewActivity = new ThemePreviewActivity(tL_wallPaper2, (Bitmap) null);
            TLRPC.WallPaperSettings wallPaperSettings2 = tL_wallPaper.settings;
            themePreviewActivity.setInitialModes(wallPaperSettings2.blur, wallPaperSettings2.motion, wallPaperSettings2.intensity);
        }
    }

    public static void createCustomMention(final Activity activity, String name, final ActionTextDelegate delegate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(LocaleController.getString("CreateMention", R.string.CreateMention));
        final EditTextBoldCursor editTextBoldCursor = new EditTextBoldCursor(activity) {
            @Override
            public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64.0f), 1073741824));
            }
        };
        editTextBoldCursor.setTextSize(1, 18.0f);
        editTextBoldCursor.setText(name);
        editTextBoldCursor.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
        editTextBoldCursor.setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        editTextBoldCursor.setSingleLine(true);
        editTextBoldCursor.setFocusable(true);
        editTextBoldCursor.setInputType(1);
        editTextBoldCursor.setTransformHintToHeader(true);
        editTextBoldCursor.setLineColors(Theme.getColor(Theme.key_dialogInputField), Theme.getColor(Theme.key_dialogInputFieldActivated), Theme.getColor(Theme.key_text_RedBold));
        editTextBoldCursor.setImeOptions(6);
        editTextBoldCursor.setBackgroundDrawable(null);
        editTextBoldCursor.requestFocus();
        editTextBoldCursor.setPadding(0, 0, 0, 0);
        editTextBoldCursor.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });
        builder.setView(editTextBoldCursor);
        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                PlusUtils.lambda$createCustomMention$17(EditTextBoldCursor.this, delegate, activity, dialogInterface, i);
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        final AlertDialog create = builder.create();
        final CharSequence text = ((ClipboardManager) ApplicationLoader.applicationContext.getSystemService("clipboard")).getText();
        final boolean z = text != null && text.length() > 0 && text.toString().matches("-?(0|[1-9]\\d*)");
        if (z) {
            builder.setNeutralButton(LocaleController.getString("Paste", android.R.string.paste), (DialogInterface.OnClickListener) null);
        }
        create.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public final void onShow(DialogInterface dialogInterface) {
                PlusUtils.lambda$createCustomMention$19(EditTextBoldCursor.this, z, create, text, dialogInterface);
            }
        });
        create.show();
        ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) editTextBoldCursor.getLayoutParams();
        if (marginLayoutParams != null) {
            if (marginLayoutParams instanceof FrameLayout.LayoutParams) {
                ((FrameLayout.LayoutParams) marginLayoutParams).gravity = 1;
            }
            int dp = AndroidUtilities.dp(24.0f);
            marginLayoutParams.leftMargin = dp;
            marginLayoutParams.rightMargin = dp;
            marginLayoutParams.height = AndroidUtilities.dp(36.0f);
            editTextBoldCursor.setLayoutParams(marginLayoutParams);
        }
        editTextBoldCursor.setSelection(0, editTextBoldCursor.getText().length());
    }

    public static void lambda$createCustomMention$17(EditTextBoldCursor editTextBoldCursor, ActionTextDelegate actionTextDelegate, Activity activity, DialogInterface dialogInterface, int i) {
        if (TextUtils.isEmpty(editTextBoldCursor.getText())) {
            showToast(activity, LocaleController.getString("UserRestricted", R.string.UserRestricted));
        } else if (actionTextDelegate != null) {
            actionTextDelegate.onCompleted(editTextBoldCursor.getText().toString());
        }
    }

    public static void lambda$createCustomMention$19(final EditTextBoldCursor editTextBoldCursor, boolean z, AlertDialog alertDialog, final CharSequence charSequence, DialogInterface dialogInterface) {
        editTextBoldCursor.requestFocus();
        AndroidUtilities.showKeyboard(editTextBoldCursor);
        if (z) {
            alertDialog.getButton(-3).setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    EditTextBoldCursor.this.setText(charSequence);
                }
            });
        }
    }

    public static void shareTheme(Activity activity, String name) {
        if (!name.endsWith(".attheme")) {
            name = name + ".attheme";
        }
        File file = new File(FileLoader.getDirectory(4), FileLoader.fixFileName(name));
        try {
            if (AndroidUtilities.copyFile(new File(ApplicationLoader.getFilesDirFixed(), "remote" + loadingTheme.id + ".attheme"), file)) {
                Intent intent = new Intent("android.intent.action.SEND");
                intent.setType("text/xml");
                if (Build.VERSION.SDK_INT >= 24) {
                    try {
                        intent.putExtra("android.intent.extra.STREAM", FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file));
                        intent.setFlags(1);
                    } catch (Exception unused) {
                        intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(file));
                    }
                } else {
                    intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(file));
                }
                activity.startActivityForResult(Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)), 500);
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }

    public static void setFilterEmoticon(MessagesController$DialogFilter filter, boolean save) {
        if (!filter.local) {
            String string = MessagesController.getMainSettings(UserConfig.selectedAccount).getString(filter.name + "_icon", null);
            if (string != null) {
                filter.emoticon = string;
                return;
            }
        }
        setFilterEmoticonByType(filter);
        if (filter.emoticon == null) {
            setFilterEmoticonByFlags(filter, !filter.local);
        }
    }

    private static void setFilterEmoticonByType(MessagesController$DialogFilter filter) {
        switch (filter.type) {
            case 20:
                filter.emoticon = "👤";
                break;
            case 21:
            case 22:
            case 23:
                filter.emoticon = "👥";
                break;
            case 24:
                filter.emoticon = "📢";
                break;
            case 25:
                filter.emoticon = "🤖";
                break;
            case 26:
                filter.emoticon = "⭐";
                break;
            case 27:
                filter.emoticon = "👑";
                break;
            case 28:
                filter.emoticon = "✅";
                break;
            case 29:
                filter.emoticon = "🔔";
                break;
        }
    }

    public static void setFilterEmoticonByFlags(org.telegram.messenger.MessagesController$DialogFilter r3, boolean r4) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.setFilterEmoticonByFlags(org.telegram.messenger.MessagesController$DialogFilter, boolean):void");
    }

    public static int getFilterEmoticonInt(MessagesController$DialogFilter filter) {
        return getFilterEmoticonInt(filter.emoticon, filter.type, filter.local);
    }

    public static int getFilterEmoticonInt(String emoticon, int type, boolean local) {
        char c;
        if (TextUtils.isEmpty(emoticon)) {
            if (!local) {
                return Theme.tabEmoticonsInt[5];
            }
        } else {
            if (PlusSettings.changeEmojiToIcon || local) {
                switch (emoticon.hashCode()) {
                    case 9917:
                        if (emoticon.equals("⚽")) {
                            c = '\n';
                            break;
                        }
                        c = 65535;
                        break;
                    case 9989:
                        if (emoticon.equals("✅")) {
                            c = 24;
                            break;
                        }
                        c = 65535;
                        break;
                    case 9992:
                        if (emoticon.equals("✈")) {
                            c = 19;
                            break;
                        }
                        c = 65535;
                        break;
                    case 10084:
                        if (emoticon.equals("❤")) {
                            c = '\f';
                            break;
                        }
                        c = 65535;
                        break;
                    case 11088:
                        if (emoticon.equals("⭐")) {
                            c = 4;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772436:
                        if (emoticon.equals("🐱")) {
                            c = '\t';
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772468:
                        if (emoticon.equals("👑")) {
                            c = 20;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772487:
                        if (emoticon.equals("👤")) {
                            c = 0;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772488:
                        if (emoticon.equals("👥")) {
                            c = 1;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772548:
                        if (emoticon.equals("💡")) {
                            c = 30;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772559:
                        if (emoticon.equals("💬")) {
                            c = 23;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772563:
                        if (emoticon.equals("💰")) {
                            c = 25;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772575:
                        if (emoticon.equals("💼")) {
                            c = 11;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772580:
                        if (emoticon.equals("📁")) {
                            c = 7;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772587:
                        if (emoticon.equals("📈")) {
                            c = '\b';
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772590:
                        if (emoticon.equals("📋")) {
                            c = 18;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772600:
                        if (emoticon.equals("📕")) {
                            c = 26;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772613:
                        if (emoticon.equals("📢")) {
                            c = 2;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772635:
                        if (emoticon.equals("📸")) {
                            c = 28;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772660:
                        if (emoticon.equals("🔑")) {
                            c = 5;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772663:
                        if (emoticon.equals("🔔")) {
                            c = 14;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1772696:
                        if (emoticon.equals("🤖")) {
                            c = 3;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773134:
                        if (emoticon.equals("🛫")) {
                            c = 31;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773181:
                        if (emoticon.equals("🌹")) {
                            c = '\r';
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773244:
                        if (emoticon.equals("🍸")) {
                            c = 22;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773271:
                        if (emoticon.equals("🎓")) {
                            c = 17;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773292:
                        if (emoticon.equals("🎨")) {
                            c = 27;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773297:
                        if (emoticon.equals("🎭")) {
                            c = 21;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773298:
                        if (emoticon.equals("🎮")) {
                            c = 16;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773305:
                        if (emoticon.equals("🎵")) {
                            c = 29;
                            break;
                        }
                        c = 65535;
                        break;
                    case 1773348:
                        if (emoticon.equals("🏠")) {
                            c = 15;
                            break;
                        }
                        c = 65535;
                        break;
                    default:
                        c = 65535;
                        break;
                }
                switch (c) {
                    case 0:
                        return Theme.tabEmoticonsInt[0];
                    case 1:
                        return type == 21 ? Theme.tabEmoticonsInt[1] : R.drawable.tab_sgroups_new;
                    case 2:
                        return Theme.tabEmoticonsInt[2];
                    case 3:
                        return Theme.tabEmoticonsInt[3];
                    case 4:
                        return Theme.tabEmoticonsInt[4];
                    case 5:
                        return R.drawable.tab_admin_new;
                    case 6:
                    case 7:
                    default:
                        return Theme.tabEmoticonsInt[5];
                    case '\b':
                        return Theme.tabEmoticonsInt[6];
                    case '\t':
                        return Theme.tabEmoticonsInt[7];
                    case '\n':
                        return Theme.tabEmoticonsInt[8];
                    case 11:
                        return Theme.tabEmoticonsInt[9];
                    case '\f':
                        return Theme.tabEmoticonsInt[10];
                    case '\r':
                        return Theme.tabEmoticonsInt[11];
                    case 14:
                        return local ? R.drawable.msg_unmute : Theme.tabEmoticonsInt[12];
                    case 15:
                        return Theme.tabEmoticonsInt[13];
                    case 16:
                        return Theme.tabEmoticonsInt[14];
                    case 17:
                        return Theme.tabEmoticonsInt[15];
                    case 18:
                        return Theme.tabEmoticonsInt[16];
                    case 19:
                        return Theme.tabEmoticonsInt[17];
                    case 20:
                        return local ? R.drawable.tab_admin_new : Theme.tabEmoticonsInt[18];
                    case 21:
                        return Theme.tabEmoticonsInt[19];
                    case 22:
                        return Theme.tabEmoticonsInt[20];
                    case 23:
                        return Theme.tabEmoticonsInt[21];
                    case 24:
                        return local ? R.drawable.tab_unread_new : Theme.tabEmoticonsInt[22];
                    case 25:
                        return Theme.tabEmoticonsInt[23];
                    case 26:
                        return Theme.tabEmoticonsInt[24];
                    case 27:
                        return Theme.tabEmoticonsInt[25];
                    case 28:
                        return Theme.tabEmoticonsInt[26];
                    case 29:
                        return Theme.tabEmoticonsInt[27];
                    case R.styleable.AppCompatTheme_actionModeTheme:
                        return Theme.tabEmoticonsInt[28];
                    case R.styleable.AppCompatTheme_actionModeWebSearchDrawable:
                        return Theme.tabEmoticonsInt[29];
                }
            }
            if (Emoji.getEmojiDrawable(emoticon) != null) {
                return -1;
            }
        }
        return 0;
    }

    public static boolean isUsers(MessagesController$DialogFilter filter) {
        if (filter == null) {
            return false;
        }
        int i = filter.flags;
        if (i != 1 && i != 2 && i != 3) {
            switch (i) {
                case 129:
                case 130:
                case 131:
                    break;
                default:
                    return false;
            }
        }
        return true;
    }

    public static void fixLocalFiltersIssue(org.telegram.messenger.MessagesController$DialogFilter r7) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.fixLocalFiltersIssue(org.telegram.messenger.MessagesController$DialogFilter):void");
    }

    public static MessagesController$DialogFilter addLocalFilter(int type, BaseFragment fragment, boolean atBegin) {
        return addLocalFilter(null, type, fragment, atBegin);
    }

    public static String getTextByMessageType(TLRPC.Message message) {
        TLRPC.MessageMedia messageMedia = message.media;
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (MessageObject.isPhoto(message)) {
            return LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
        }
        if (MessageObject.isLocationMessage(message)) {
            return LocaleController.getString("AttachLocation", R.string.AttachLocation);
        }
        if (MessageObject.isVoiceMessage(message)) {
            return LocaleController.getString("AttachAudio", R.string.AttachAudio);
        }
        if (MessageObject.isVideoMessage(message)) {
            return LocaleController.getString("AttachVideo", R.string.AttachVideo);
        }
        if (MessageObject.isGifMessage(message)) {
            return LocaleController.getString("AttachGif", R.string.AttachGif);
        }
        if (MessageObject.isMusicMessage(message)) {
            return LocaleController.getString("AttachMusic", R.string.AttachMusic);
        }
        if (MessageObject.isStickerMessage(message)) {
            return LocaleController.getString("AttachSticker", R.string.AttachSticker);
        }
        if (messageMedia instanceof TLRPC.TL_messageMediaPhoto) {
            return LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
        }
        if (messageMedia instanceof TLRPC.TL_messageMediaDocument) {
            return LocaleController.getString("AttachDocument", R.string.AttachDocument);
        }
        if (messageMedia.video_unused != null) {
            return LocaleController.getString("AttachVideo", R.string.AttachVideo);
        }
        if (messageMedia.document != null) {
            return LocaleController.getString("AttachDocument", R.string.AttachDocument);
        }
        if (messageMedia.geo != null) {
            return LocaleController.getString("AttachLocation", R.string.AttachLocation);
        }
        return LocaleController.getString("SharedMediaTab2", R.string.SharedMediaTab2);
    }

    public static MessagesController$DialogFilter addLocalFilter(String name, int type, BaseFragment fragment, boolean atBegin) {
        MessagesController messagesController = AccountInstance.getInstance(UserConfig.selectedAccount).getMessagesController();
        MessagesController$DialogFilter messagesController$DialogFilter = type == 0 ? null : (MessagesController$DialogFilter) messagesController.dialogFiltersByType.get(type);
        if (messagesController$DialogFilter == null) {
            messagesController$DialogFilter = new MessagesController$DialogFilter();
            messagesController$DialogFilter.id = 2;
            messagesController$DialogFilter.pendingUnreadCount = -1;
            while (messagesController.dialogFiltersById.get(messagesController$DialogFilter.id) != null) {
                messagesController$DialogFilter.id++;
            }
            messagesController$DialogFilter.type = type;
            messagesController$DialogFilter.local = true;
            if (type != 0) {
                switch (type) {
                    case 20:
                        messagesController$DialogFilter.name = LocaleController.getString("Users", R.string.Users);
                        int i = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                        messagesController$DialogFilter.flags = i;
                        int i2 = i | MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                        messagesController$DialogFilter.flags = i2;
                        messagesController$DialogFilter.flags = i2 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideUsersTab;
                        break;
                    case 21:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterGroups", R.string.FilterGroups);
                        int i3 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                        messagesController$DialogFilter.flags = i3;
                        messagesController$DialogFilter.flags = i3 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideGroupsTab;
                        break;
                    case 22:
                        messagesController$DialogFilter.name = LocaleController.getString("SuperGroups", R.string.SuperGroups);
                        int i4 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                        messagesController$DialogFilter.flags = i4;
                        messagesController$DialogFilter.flags = i4 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideSuperGroupsTab;
                        break;
                    case 23:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterGroups", R.string.FilterGroups);
                        int i5 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                        messagesController$DialogFilter.flags = i5;
                        messagesController$DialogFilter.flags = i5 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideSuperGroupsTab;
                        break;
                    case 24:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterChannels", R.string.FilterChannels);
                        int i6 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                        messagesController$DialogFilter.flags = i6;
                        messagesController$DialogFilter.flags = i6 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideChannelsTab;
                        break;
                    case 25:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterBots", R.string.FilterBots);
                        int i7 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_BOTS;
                        messagesController$DialogFilter.flags = i7;
                        messagesController$DialogFilter.flags = i7 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideBotsTab;
                        break;
                    case 26:
                        messagesController$DialogFilter.name = LocaleController.getString("Favorites", R.string.Favorites);
                        messagesController$DialogFilter.hide = Theme.plusHideFavsTab;
                        int size = messagesController.favsDialogs.size();
                        for (int i8 = 0; i8 < size; i8++) {
                            long longValue = ((Long) messagesController.favsDialogs.get(i8)).longValue();
                            if (!messagesController$DialogFilter.alwaysShow.contains(Long.valueOf(longValue))) {
                                messagesController$DialogFilter.alwaysShow.add(Long.valueOf(longValue));
                            }
                        }
                        break;
                    case 27:
                        messagesController$DialogFilter.name = LocaleController.getString("Administrator", R.string.Administrator);
                        messagesController$DialogFilter.flags |= MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideAdminTab;
                        int size2 = messagesController.getDialogsByType(type, 0).size();
                        for (int i9 = 0; i9 < size2; i9++) {
                            if (messagesController.getDialogsByType(type, 0).get(i9) instanceof TLRPC.TL_dialog) {
                                long j = ((TLRPC.Dialog) messagesController.getDialogsByType(type, 0).get(i9)).id;
                                if (!messagesController$DialogFilter.alwaysShow.contains(Integer.valueOf((int) j))) {
                                    messagesController$DialogFilter.alwaysShow.add(Long.valueOf(j));
                                }
                            }
                        }
                        break;
                    case 28:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterUnread", R.string.FilterUnread);
                        int i10 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_ALL_CHATS;
                        messagesController$DialogFilter.flags = i10;
                        int i11 = i10 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
                        messagesController$DialogFilter.flags = i11;
                        messagesController$DialogFilter.flags = i11 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideUnreadTab;
                        break;
                    case 29:
                        messagesController$DialogFilter.name = LocaleController.getString("FilterUnmuted", R.string.FilterUnmuted);
                        int i12 = messagesController$DialogFilter.flags | MessagesController.DIALOG_FILTER_FLAG_ALL_CHATS;
                        messagesController$DialogFilter.flags = i12;
                        int i13 = i12 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                        messagesController$DialogFilter.flags = i13;
                        messagesController$DialogFilter.flags = i13 | MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        messagesController$DialogFilter.hide = Theme.plusHideUnmutedTab;
                        break;
                    default:
                        return null;
                }
            } else if (name != null) {
                messagesController$DialogFilter.name = name;
            }
            messagesController.dialogFiltersByType.put(messagesController$DialogFilter.type, messagesController$DialogFilter);
            FilterCreateActivity.saveFilterToServer(messagesController$DialogFilter, messagesController$DialogFilter.flags, messagesController$DialogFilter.name, messagesController$DialogFilter.color, new ArrayList(messagesController$DialogFilter.alwaysShow), new ArrayList(messagesController$DialogFilter.neverShow), messagesController$DialogFilter.pinnedDialogs.clone(), true, atBegin, true, true, false, fragment, new Runnable() {
                @Override
                public final void run() {
                    PlusUtils.lambda$addLocalFilter$20();
                }
            });
        }
        return messagesController$DialogFilter;
    }

    public static void lambda$addLocalFilter$20() {
        NotificationCenter.getInstance(UserConfig.selectedAccount).lambda$postNotificationNameOnUIThread$1(NotificationCenter.dialogFiltersUpdated, new Object[0]);
    }

    public static void showAddToFolder(BaseFragment fragment, long dialog_id) {
        showAddToFolder(fragment, dialog_id, null);
    }

    public static void showAddToFolder(final BaseFragment fragment, final long dialog_id, ArrayList<Long> selectedDialogs) {
        if (fragment == null || fragment.getParentActivity() == null) {
            return;
        }
        final ArrayList arrayList = new ArrayList();
        if (selectedDialogs != null && !selectedDialogs.isEmpty()) {
            arrayList.addAll(selectedDialogs);
        } else {
            arrayList.add(Long.valueOf(dialog_id));
        }
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$showAddToFolder$25(arrayList, fragment, dialog_id);
            }
        });
    }

    public static void lambda$showAddToFolder$25(final ArrayList arrayList, final BaseFragment baseFragment, final long j) {
        final int i = UserConfig.selectedAccount;
        MessagesController messagesController = AccountInstance.getInstance(i).getMessagesController();
        final ArrayList arrayList2 = new ArrayList();
        boolean z = false;
        for (int i2 = 0; i2 < messagesController.dialogFilters.size(); i2++) {
            MessagesController$DialogFilter messagesController$DialogFilter = (MessagesController$DialogFilter) messagesController.dialogFilters.get(i2);
            if (!messagesController$DialogFilter.local || messagesController$DialogFilter.flags == 0) {
                arrayList2.add(messagesController$DialogFilter);
            }
        }
        int size = arrayList.size();
        final int size2 = arrayList2.size();
        if (size2 > 0) {
            final boolean[] zArr = new boolean[size2];
            final BottomSheet.Builder builder = new BottomSheet.Builder(baseFragment.getParentActivity());
            builder.setApplyTopPadding(false);
            builder.setApplyBottomPadding(false);
            ScrollView scrollView = new ScrollView(baseFragment.getParentActivity());
            int i3 = 1;
            scrollView.setFillViewport(true);
            int i4 = Theme.key_windowBackgroundGray;
            scrollView.setTag(Integer.valueOf(i4));
            scrollView.setBackgroundColor(Theme.usePlusTheme ? Theme.prefShadowColor : Theme.getColor(i4));
            LinearLayout linearLayout = new LinearLayout(baseFragment.getParentActivity());
            linearLayout.setOrientation(1);
            scrollView.addView(linearLayout, new FrameLayout.LayoutParams(-1, -2));
            int i5 = 0;
            while (i5 < size2) {
                final MessagesController$DialogFilter messagesController$DialogFilter2 = (MessagesController$DialogFilter) arrayList2.get(i5);
                String str = messagesController$DialogFilter2.name;
                ArrayList<Long> arrayList3 = messagesController$DialogFilter2.alwaysShow;
                if (size == i3) {
                    zArr[i5] = arrayList3 != null && arrayList3.contains(Long.valueOf(j));
                }
                CheckBoxCell checkBoxCell = new CheckBoxCell(baseFragment.getParentActivity(), i3);
                checkBoxCell.setTag(Integer.valueOf(i5));
                checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(z));
                linearLayout.addView((View) checkBoxCell, (ViewGroup.LayoutParams) LayoutHelper.createLinear(-1, -2));
                checkBoxCell.setText(str, BuildConfig.APP_CENTER_HASH, zArr[i5], true);
                checkBoxCell.setTextColor(Theme.usePlusTheme ? Theme.dialogTextColor : Theme.getColor(Theme.key_dialogTextBlack));
                LinearLayout linearLayout2 = linearLayout;
                final MessagesController messagesController2 = messagesController;
                final ScrollView scrollView2 = scrollView;
                checkBoxCell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public final void onClick(View view) {
                        PlusUtils.lambda$showAddToFolder$21(zArr, baseFragment, messagesController$DialogFilter2, arrayList, messagesController2, scrollView2, i, view);
                    }
                });
                i5++;
                messagesController = messagesController;
                size = size;
                linearLayout = linearLayout2;
                scrollView = scrollView;
                i3 = 1;
                z = false;
            }
            LinearLayout linearLayout3 = linearLayout;
            ScrollView scrollView3 = scrollView;
            final int i6 = size;
            BottomSheet.BottomSheetCell bottomSheetCell = new BottomSheet.BottomSheetCell(baseFragment.getParentActivity(), 1);
            bottomSheetCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
            bottomSheetCell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0);
            bottomSheetCell.setTextColor(Theme.usePlusTheme ? Theme.dialogTextColor : Theme.getColor(Theme.key_dialogTextBlue2));
            bottomSheetCell.setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    PlusUtils.lambda$showAddToFolder$24(builder, size2, arrayList2, j, zArr, i6, arrayList, baseFragment, i, view);
                }
            });
            linearLayout3.addView((View) bottomSheetCell, (ViewGroup.LayoutParams) LayoutHelper.createLinear(-1, -2, 83));
            builder.setCustomView(scrollView3);
            baseFragment.showDialog(builder.create());
        }
    }

    public static void lambda$showAddToFolder$21(boolean[] zArr, BaseFragment baseFragment, MessagesController$DialogFilter messagesController$DialogFilter, ArrayList arrayList, MessagesController messagesController, View view, int i, View view2) {
        CheckBoxCell checkBoxCell = (CheckBoxCell) view2;
        int intValue = ((Integer) checkBoxCell.getTag()).intValue();
        if (!zArr[intValue]) {
            try {
                ArrayList<Long> dialogsCount = FiltersListBottomSheet.getDialogsCount(baseFragment, messagesController$DialogFilter, arrayList, true, false);
                int size = messagesController$DialogFilter != null ? messagesController$DialogFilter.alwaysShow.size() : 0;
                int size2 = dialogsCount.size() + size;
                if ((size2 > messagesController.dialogFiltersChatsLimitDefault && !UserConfig.getInstance(size).isPremium()) || size2 > messagesController.dialogFiltersChatsLimitPremium) {
                    baseFragment.showDialog(new LimitReachedBottomSheet(baseFragment, view.getContext(), 4, i, (Theme.ResourcesProvider) null));
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        zArr[intValue] = !zArr[intValue];
        checkBoxCell.setChecked(zArr[intValue], true);
    }

    public static void lambda$showAddToFolder$24(BottomSheet.Builder builder, final int i, final ArrayList arrayList, final long j, final boolean[] zArr, final int i2, final ArrayList arrayList2, final BaseFragment baseFragment, final int i3, View view) {
        builder.create().dismiss();
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$showAddToFolder$23(i, arrayList, j, zArr, i2, arrayList2, baseFragment, i3);
            }
        });
    }

    public static void lambda$showAddToFolder$23(int r23, java.util.ArrayList r24, long r25, boolean[] r27, int r28, java.util.ArrayList r29, final org.telegram.ui.ActionBar.BaseFragment r30, final int r31) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.lambda$showAddToFolder$23(int, java.util.ArrayList, long, boolean[], int, java.util.ArrayList, org.telegram.ui.ActionBar.BaseFragment, int):void");
    }

    public static void lambda$showAddToFolder$22(BaseFragment baseFragment, MessagesController$DialogFilter messagesController$DialogFilter, int i) {
        showToast(baseFragment.getParentActivity(), LocaleController.formatString("FolderUpdated", R.string.FolderUpdated, new Object[]{messagesController$DialogFilter.name}));
        NotificationCenter.getInstance(i).lambda$postNotificationNameOnUIThread$1(NotificationCenter.dialogFiltersUpdated, new Object[0]);
    }

    public static void updateFavs(int currentAccount, long dialog_id) {
        boolean contains = MessagesController.getInstance(currentAccount).favsDialogs.contains(Long.valueOf(dialog_id));
        TLRPC.Dialog dialog = (TLRPC.Dialog) MessagesController.getInstance(currentAccount).dialogs_dict.get(dialog_id);
        if (dialog == null) {
            return;
        }
        if (contains) {
            MessagesController.getInstance(currentAccount).getDialogs(26, dialog.folder_id).remove(dialog);
        } else {
            MessagesController.getInstance(currentAccount).getDialogs(26, dialog.folder_id).add(dialog);
        }
        PlusRepository.getInstance(currentAccount).insertOrUpdateFavorite(new DialogEntity(UserConfig.getInstance(currentAccount).clientUserId, dialog_id, !contains, MessagesController.getInstance(currentAccount).hiddenDialogs.contains(Long.valueOf(DialogObject.isEncryptedDialog(dialog_id) ? DialogObject.getEncryptedChatId(dialog_id) : dialog_id))));
    }

    public static boolean isFavFilter(MessagesController$DialogFilter filter) {
        if (filter.type == 26) {
            return true;
        }
        String str = filter.name;
        if (str == null) {
            str = BuildConfig.APP_CENTER_HASH;
        }
        int i = R.string.Favorites;
        return str.equals(LocaleController.getString("Favorites", i)) || str.equals(LocaleController.getEnglishString(i));
    }

    public static void resetFolders(final BaseFragment fragment, final boolean restart) {
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$resetFolders$27(fragment, restart);
            }
        });
    }

    public static void lambda$resetFolders$27(final BaseFragment baseFragment, final boolean z) {
        final int i = UserConfig.selectedAccount;
        final MessagesController messagesController = AccountInstance.getInstance(i).getMessagesController();
        final MessagesStorage messagesStorage = AccountInstance.getInstance(i).getMessagesStorage();
        AlertDialog.Builder builder = new AlertDialog.Builder(baseFragment.getParentActivity());
        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
        int i2 = messagesController.remoteFoldersCount - 1;
        String str = LocaleController.getString("ResetFolders", R.string.ResetFolders) + ": Cloud " + i2 + " Local " + ((messagesController.dialogFilters.size() - 1) - i2);
        if (messagesStorage.foldersError) {
            str = str + "\n\n" + LocaleController.getString("SecretChatsLost", R.string.SecretChatsLost);
        }
        builder.setMessage(str);
        builder.setPositiveButton(LocaleController.getString("Yes", R.string.Yes).toUpperCase(), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i3) {
                PlusUtils.lambda$resetFolders$26(messagesController, messagesStorage, z, i, baseFragment, dialogInterface, i3);
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        baseFragment.showDialog(builder.create());
    }

    public static void lambda$resetFolders$26(MessagesController messagesController, MessagesStorage messagesStorage, boolean z, int i, final BaseFragment baseFragment, DialogInterface dialogInterface, int i2) {
        ArrayList arrayList = messagesController.dialogFilters;
        int size = arrayList.size();
        clearFiltersPreferences = true;
        for (int i3 = 0; i3 < size; i3++) {
            saveLocalFilter((MessagesController$DialogFilter) arrayList.get(i3));
            messagesStorage.deleteDialogFilter((MessagesController$DialogFilter) arrayList.get(i3));
        }
        messagesController.dialogFilters.clear();
        messagesController.dialogFiltersById.clear();
        messagesController.dialogFiltersByType.clear();
        if (messagesStorage.foldersError) {
            messagesStorage.recoverDatabase();
        }
        if (z) {
            MessagesController.getMainSettings(i).edit().putBoolean("localFiltersLoaded_", false).apply();
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    PlusUtils.restartApp(baseFragment.getParentActivity());
                }
            }, 500L);
        }
    }

    public static void saveLocalFilter(final MessagesController$DialogFilter filter) {
        boolean z;
        SharedPreferences sharedPreferences;
        ArrayList<TLRPC.InputPeer> arrayList;
        ArrayList<Long> arrayList2;
        long j;
        if (filter.local) {
            int i = UserConfig.selectedAccount;
            int i2 = filter.flags;
            TLRPC.TL_dialogFilter tL_dialogFilter = new TLRPC.TL_dialogFilter();
            int i3 = tL_dialogFilter.flags | 1;
            tL_dialogFilter.flags = i3;
            tL_dialogFilter.contacts = (MessagesController.DIALOG_FILTER_FLAG_CONTACTS & i2) != 0;
            tL_dialogFilter.non_contacts = (MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS & i2) != 0;
            tL_dialogFilter.groups = (MessagesController.DIALOG_FILTER_FLAG_GROUPS & i2) != 0;
            tL_dialogFilter.broadcasts = (MessagesController.DIALOG_FILTER_FLAG_CHANNELS & i2) != 0;
            tL_dialogFilter.bots = (MessagesController.DIALOG_FILTER_FLAG_BOTS & i2) != 0;
            tL_dialogFilter.exclude_muted = (MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED & i2) != 0;
            tL_dialogFilter.exclude_read = (MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ & i2) != 0;
            tL_dialogFilter.exclude_archived = (i2 & MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED) != 0;
            tL_dialogFilter.id = filter.id;
            tL_dialogFilter.title = filter.name;
            int i4 = filter.color;
            if (i4 < 0) {
                tL_dialogFilter.flags = (-134217729) & i3;
                tL_dialogFilter.color = 0;
            } else {
                tL_dialogFilter.flags = i3 | 134217728;
                tL_dialogFilter.color = i4;
            }
            String str = filter.emoticon;
            if (str != null) {
                tL_dialogFilter.flags |= 33554432;
                tL_dialogFilter.emoticon = str;
            }
            tL_dialogFilter.local = true;
            tL_dialogFilter.type = filter.type;
            MessagesController messagesController = AccountInstance.getInstance(i).getMessagesController();
            if (filter.type == 26) {
                long j2 = UserConfig.getInstance(i).clientUserId;
                int i5 = 0;
                while (i5 < messagesController.favsDialogs.size()) {
                    long longValue = ((Long) messagesController.favsDialogs.get(i5)).longValue();
                    if (filter.alwaysShow.contains(Long.valueOf(longValue))) {
                        j = j2;
                    } else {
                        j = j2;
                        PlusRepository.getInstance(i).insertOrUpdateFavorite(new DialogEntity(j2, longValue, false, false));
                    }
                    i5++;
                    j2 = j;
                }
                long j3 = j2;
                for (int i6 = 0; i6 < filter.alwaysShow.size(); i6++) {
                    long longValue2 = filter.alwaysShow.get(i6).longValue();
                    if (!messagesController.favsDialogs.contains(Long.valueOf(longValue2))) {
                        PlusRepository.getInstance(i).insertOrUpdateFavorite(new DialogEntity(j3, longValue2, true, false));
                    }
                }
                for (int i7 = 0; i7 < filter.neverShow.size(); i7++) {
                    long longValue3 = filter.neverShow.get(i7).longValue();
                    if (messagesController.favsDialogs.contains(Long.valueOf(longValue3))) {
                        PlusRepository.getInstance(i).insertOrUpdateFavorite(new DialogEntity(j3, longValue3, false, false));
                    }
                }
            }
            ArrayList<Long> arrayList3 = new ArrayList<>();
            if (filter.pinnedDialogs.size() != 0) {
                int size = filter.pinnedDialogs.size();
                for (int i8 = 0; i8 < size; i8++) {
                    long keyAt = filter.pinnedDialogs.keyAt(i8);
                    if (!DialogObject.isEncryptedDialog(keyAt)) {
                        arrayList3.add(Long.valueOf(keyAt));
                    }
                }
                Collections.sort(arrayList3, new Comparator() {
                    @Override
                    public final int compare(Object obj, Object obj2) {
                        int lambda$saveLocalFilter$28;
                        lambda$saveLocalFilter$28 = PlusUtils.lambda$saveLocalFilter$28(MessagesController$DialogFilter.this, (Long) obj, (Long) obj2);
                        return lambda$saveLocalFilter$28;
                    }
                });
            }
            for (int i9 = 0; i9 < 3; i9++) {
                if (i9 == 0) {
                    arrayList2 = filter.alwaysShow;
                    arrayList = tL_dialogFilter.include_peers;
                } else if (i9 == 1) {
                    arrayList2 = filter.neverShow;
                    arrayList = tL_dialogFilter.exclude_peers;
                } else {
                    arrayList = tL_dialogFilter.pinned_peers;
                    arrayList2 = arrayList3;
                }
                int size2 = arrayList2.size();
                for (int i10 = 0; i10 < size2; i10++) {
                    long longValue4 = arrayList2.get(i10).longValue();
                    if ((i9 != 0 || filter.pinnedDialogs.indexOfKey(longValue4) < 0) && !DialogObject.isEncryptedDialog(longValue4)) {
                        if (longValue4 > 0) {
                            TLRPC.User user = messagesController.getUser(Long.valueOf(longValue4));
                            if (user != null) {
                                TLRPC.TL_inputPeerUser tL_inputPeerUser = new TLRPC.TL_inputPeerUser();
                                tL_inputPeerUser.user_id = longValue4;
                                tL_inputPeerUser.access_hash = user.access_hash;
                                arrayList.add(tL_inputPeerUser);
                            }
                        } else {
                            long j4 = -longValue4;
                            TLRPC.Chat chat = messagesController.getChat(Long.valueOf(j4));
                            if (chat != null) {
                                if (ChatObject.isChannel(chat)) {
                                    TLRPC.TL_inputPeerChannel tL_inputPeerChannel = new TLRPC.TL_inputPeerChannel();
                                    tL_inputPeerChannel.channel_id = j4;
                                    tL_inputPeerChannel.access_hash = chat.access_hash;
                                    arrayList.add(tL_inputPeerChannel);
                                } else {
                                    TLRPC.TL_inputPeerChat tL_inputPeerChat = new TLRPC.TL_inputPeerChat();
                                    tL_inputPeerChat.chat_id = j4;
                                    arrayList.add(tL_inputPeerChat);
                                }
                            }
                        }
                    }
                }
            }
            if (i == 0) {
                z = false;
                sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("filters", 0);
            } else {
                z = false;
                sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("filters" + i, 0);
            }
            if (clearFiltersPreferences) {
                sharedPreferences.edit().clear().commit();
                sharedPreferences.edit().putBoolean("restore", true).apply();
                clearFiltersPreferences = z;
            }
            SerializedData serializedData = new SerializedData(tL_dialogFilter.getObjectSize());
            tL_dialogFilter.serializeToStream(serializedData);
            String str2 = tL_dialogFilter.title;
            int i11 = filter.order;
            sharedPreferences.edit().putString(str2 + "_" + filter.type + "_" + i11, Utilities.bytesToHex(serializedData.toByteArray())).apply();
            serializedData.cleanup();
        }
    }

    public static int lambda$saveLocalFilter$28(MessagesController$DialogFilter messagesController$DialogFilter, Long l, Long l2) {
        int i = messagesController$DialogFilter.pinnedDialogs.get(l.longValue());
        int i2 = messagesController$DialogFilter.pinnedDialogs.get(l2.longValue());
        if (i > i2) {
            return 1;
        }
        return i < i2 ? -1 : 0;
    }

    public static ArrayList<TLRPC.DialogFilter> restoreLocalFolders() {
        SharedPreferences sharedPreferences;
        int i = UserConfig.selectedAccount;
        if (i == 0) {
            sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("filters", 0);
        } else {
            sharedPreferences = ApplicationLoader.applicationContext.getSharedPreferences("filters" + i, 0);
        }
        ArrayList<TLRPC.DialogFilter> arrayList = new ArrayList<>();
        boolean z = MessagesController.getMainSettings(i).getBoolean("localFiltersLoaded_", false);
        if (sharedPreferences.getBoolean("restore", false)) {
            if (!z) {
                Map<String, ?> all = sharedPreferences.getAll();
                ArrayList arrayList2 = new ArrayList();
                for (Map.Entry<String, ?> entry : all.entrySet()) {
                    try {
                        String key = entry.getKey();
                        Utilities.parseLong(key).longValue();
                        SerializedData serializedData = new SerializedData(Utilities.hexToBytes((String) entry.getValue()));
                        TLRPC.DialogFilter TLdeserialize = TLRPC.DialogFilter.TLdeserialize(serializedData, serializedData.readInt32(true), true);
                        if (TLdeserialize != null && !arrayList2.contains(Integer.valueOf(TLdeserialize.id))) {
                            int indexOf = key.indexOf(95);
                            int lastIndexOf = key.lastIndexOf(95);
                            int intValue = Utilities.parseInt((CharSequence) key.substring(indexOf + 1, lastIndexOf)).intValue();
                            int intValue2 = Utilities.parseInt((CharSequence) key.substring(lastIndexOf + 1)).intValue();
                            TLdeserialize.local = true;
                            TLdeserialize.type = intValue;
                            TLdeserialize.order = intValue2;
                            arrayList2.add(Integer.valueOf(TLdeserialize.id));
                        }
                        arrayList.add(TLdeserialize);
                        serializedData.cleanup();
                    } catch (Exception unused) {
                    }
                }
            } else {
                sharedPreferences.edit().remove("restore").apply();
            }
        }
        return arrayList;
    }

    public static void showTranslateDialog(Context context, String query, String toLanguage, TranslateCallBack translateCallBack) {
        AlertDialog alertDialog = progressDialog;
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        AlertDialog alertDialog2 = new AlertDialog(context, 3);
        progressDialog = alertDialog2;
        alertDialog2.showDelayed(400L);
        BaseTranslationEngine.translate(query, toLanguage, new AnonymousClass9(context, translateCallBack, query));
    }

    public class AnonymousClass9 implements BaseTranslationEngine.TranslateCallBack {
        private String fromLang;
        private String toLang;
        public final Context val$context;
        public final String val$query;
        public final TranslateCallBack val$translateCallBack;

        public AnonymousClass9(final Context val$context, final TranslateCallBack val$translateCallBack, final String val$query) {
            this.val$context = val$context;
            this.val$translateCallBack = val$translateCallBack;
            this.val$query = val$query;
        }

        @Override
        public void onSuccess(String translation, String fl, String tl) {
            this.fromLang = fl;
            this.toLang = tl;
            onSuccess(translation);
        }

        @Override
        public void onSuccess(final String translation) {
            if (PlusUtils.progressDialog != null) {
                PlusUtils.progressDialog.dismiss();
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this.val$context);
            if (!TextUtils.isEmpty(this.fromLang)) {
                builder.setTitle(this.fromLang + "-" + this.toLang);
            }
            builder.setMessage(translation);
            String upperCase = LocaleController.getString("OK", R.string.OK).toUpperCase();
            final TranslateCallBack translateCallBack = this.val$translateCallBack;
            builder.setPositiveButton(upperCase, new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.AnonymousClass9.lambda$onSuccess$0(PlusUtils.TranslateCallBack.this, translation, dialogInterface, i);
                }
            });
            String string = LocaleController.getString("Language", R.string.Language);
            final Context context = this.val$context;
            final String str = this.val$query;
            final TranslateCallBack translateCallBack2 = this.val$translateCallBack;
            builder.setNegativeButton(string, new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.showLanguageSelector(context, str, translateCallBack2, false);
                }
            });
            builder.setNeutralButton(LocaleController.getString("Copy", R.string.Copy), new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    AndroidUtilities.addToClipboard(translation);
                }
            });
            final AlertDialog show = builder.show();
            show.getButton(-2).setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AnonymousClass9 anonymousClass9 = AnonymousClass9.this;
                    PlusUtils.showLanguageSelector(anonymousClass9.val$context, anonymousClass9.val$query, anonymousClass9.val$translateCallBack, true);
                    show.dismiss();
                    return false;
                }
            });
        }

        public static void lambda$onSuccess$0(TranslateCallBack translateCallBack, String str, DialogInterface dialogInterface, int i) {
            if (translateCallBack != null) {
                translateCallBack.onSuccess(str);
            }
        }

        @Override
        public void onError(Exception error) {
            String str;
            if (PlusUtils.progressDialog != null) {
                PlusUtils.progressDialog.dismiss();
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this.val$context);
            StringBuilder sb = new StringBuilder();
            sb.append(LocaleController.getString("TranslateFailed", R.string.TranslateFailed));
            if (error != null) {
                str = "\n\n" + error.getClass();
            } else {
                str = BuildConfig.APP_CENTER_HASH;
            }
            sb.append(str);
            builder.setMessage(sb.toString());
            String string = LocaleController.getString("Retry", R.string.Retry);
            final Context context = this.val$context;
            final String str2 = this.val$query;
            builder.setPositiveButton(string, new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.showTranslateDialog(context, str2);
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
            builder.show();
        }

        public void onUnsupported(String toLang) {
            if (PlusUtils.progressDialog != null) {
                PlusUtils.progressDialog.dismiss();
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(this.val$context);
            builder.setMessage(LocaleController.getString("TranslateApiUnsupported", R.string.TranslateApiUnsupported) + "\n\n" + toLang);
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
            builder.show();
        }
    }

    public static void showLanguageSelector(Context context, String query, TranslateCallBack translateCallBack, boolean all) {
        showLanguageSelector(context, query, translateCallBack, all, true);
    }

    public static void showLanguageSelector(final Context context, final String query, final TranslateCallBack translateCallBack, boolean all, final boolean saveLang) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(LocaleController.getString("Language", R.string.Language));
        ArrayList arrayList = new ArrayList(GoogleWebTranslationEngine.getInstance().loadTargetLanguages());
        int size = arrayList.size();
        List<String> list = targetLanguagesArray;
        int size2 = list != null ? list.size() : 0;
        if (size2 == 0 || ((!all && size2 == size) || (all && size2 < size))) {
            targetLanguagesArray = new ArrayList(arrayList);
            targetLanguagesNamesArray = all ? new ArrayList(arrayList) : new ArrayList();
            int size3 = targetLanguagesArray.size();
            ArrayList arrayList2 = new ArrayList();
            for (int i = 0; i < size3; i++) {
                String str = targetLanguagesArray.get(i);
                String languageName = LocaleController.getLanguageName(str);
                if (TextUtils.isEmpty(languageName)) {
                    if (!all) {
                        arrayList2.add(str);
                    }
                } else if (!all) {
                    targetLanguagesNamesArray.add(languageName + " " + str);
                } else {
                    targetLanguagesNamesArray.set(i, languageName + " " + str);
                }
            }
            if (!all) {
                int size4 = arrayList2.size();
                for (int i2 = 0; i2 < size4; i2++) {
                    targetLanguagesArray.remove(arrayList2.get(i2));
                }
            }
        }
        List<String> list2 = targetLanguagesNamesArray;
        builder.setItems((CharSequence[]) list2.toArray(new CharSequence[list2.size()]), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i3) {
                PlusUtils.lambda$showLanguageSelector$29(saveLang, query, context, translateCallBack, dialogInterface, i3);
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        builder.show();
    }

    public static void lambda$showLanguageSelector$29(boolean z, String str, Context context, TranslateCallBack translateCallBack, DialogInterface dialogInterface, int i) {
        String str2 = targetLanguagesArray.get(i);
        lastLangSelection = str2;
        if (z) {
            PlusSettings.translationLanguage = str2;
        }
        if (str != null) {
            showTranslateDialog(context, str, targetLanguagesArray.get(i), translateCallBack);
        } else if (translateCallBack != null) {
            translateCallBack.onChanged(lastLangSelection);
        }
    }

    public void switchToAccount(Activity activity) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setMessage(BuildConfig.APP_CENTER_HASH);
        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                PlusUtils.lambda$switchToAccount$30(dialogInterface, i);
            }
        });
        builder.show();
    }

    public static void sharePlusSettings(Activity activity) {
        String str = PlusSettings.usePlusFolder() ? "/Plus" : "/Telegram";
        Utilities.savePreferencesToSD(str, "plusconfig.xml", "plusconfig.xml", false);
        try {
            String telegramPath = ImageLoader.getInstance().getTelegramPath();
            if (telegramPath.endsWith(str)) {
                telegramPath = telegramPath.replace(str, BuildConfig.APP_CENTER_HASH);
            }
            File file = new File(new File(telegramPath, str), "plusconfig.xml");
            Intent intent = new Intent("android.intent.action.SEND");
            intent.setType("text/xml");
            if (Build.VERSION.SDK_INT >= 24) {
                try {
                    intent.putExtra("android.intent.extra.STREAM", FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file));
                    intent.setFlags(1);
                } catch (Exception unused) {
                    intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(file));
                }
            } else {
                intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(file));
            }
            activity.startActivityForResult(Intent.createChooser(intent, LocaleController.getString("ShareFile", R.string.ShareFile)), 500);
        } catch (Exception e) {
            FileLog.e(e);
        }
    }

    public static void showProviderSelector(Context context, final TranslateCallBack translateCallBack) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(LocaleController.getString("TranslationProvider", R.string.TranslationProvider));
        ArrayList arrayList = new ArrayList();
        arrayList.add(LocaleController.getString("ProviderGoogleTranslate", R.string.ProviderGoogleTranslate));
        arrayList.add(LocaleController.getString("ProviderYandex", R.string.ProviderYandex));
        builder.setItems((CharSequence[]) arrayList.toArray(new CharSequence[arrayList.size()]), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                PlusUtils.lambda$showProviderSelector$31(PlusUtils.TranslateCallBack.this, dialogInterface, i);
            }
        });
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        builder.show();
    }

    public static void lambda$showProviderSelector$31(TranslateCallBack translateCallBack, DialogInterface dialogInterface, int i) {
        PlusSettings.translationProvider = i;
        PlusSettings.setTranslationProvider(i);
        if (translateCallBack != null) {
            translateCallBack.onProviderChanged(i);
        }
    }

    private static CharSequence getMessageCaption(MessageObject messageObject, MessageObject.GroupedMessages group) {
        String restrictionReason = MessagesController.getRestrictionReason(messageObject.messageOwner.restriction_reason);
        if (!TextUtils.isEmpty(restrictionReason)) {
            return restrictionReason;
        }
        CharSequence charSequence = messageObject.caption;
        if (charSequence != null) {
            return charSequence;
        }
        if (group == null) {
            return null;
        }
        int size = group.messages.size();
        CharSequence charSequence2 = null;
        for (int i = 0; i < size; i++) {
            CharSequence charSequence3 = group.messages.get(i).caption;
            if (charSequence3 != null) {
                if (charSequence2 != null) {
                    return null;
                }
                charSequence2 = charSequence3;
            }
        }
        return charSequence2;
    }

    public static void changeMessageToSpoiler(MessageObject messageObject, ChatMessageCell chatMessageCell) {
        MessageObject.GroupedMessages currentMessagesGroup = chatMessageCell.getCurrentMessagesGroup();
        CharSequence messageCaption = !TextUtils.isEmpty(messageObject.messageOwner.message) ? messageObject.messageOwner.message : getMessageCaption(messageObject, currentMessagesGroup);
        TextStyleSpan.TextStyleRun textStyleRun = new TextStyleSpan.TextStyleRun();
        textStyleRun.flags |= 256;
        MediaDataController.addStyleToText(new TextStyleSpan(textStyleRun), 0, messageCaption.length(), new SpannableStringBuilder(messageCaption), true);
        if (TextUtils.isEmpty(messageObject.messageOwner.message)) {
            setMessageCaption(messageObject, currentMessagesGroup, messageCaption);
            messageObject.forceUpdate = true;
        } else {
            messageObject.messageOwner.message = messageCaption.toString();
            if (messageObject.caption != null) {
                messageObject.caption = null;
                messageObject.generateCaption();
                messageObject.forceUpdate = true;
            }
        }
        messageObject.applyNewText();
        messageObject.resetLayout();
        chatMessageCell.requestLayout();
        chatMessageCell.invalidate();
    }

    public static void setMessageContent(MessageObject messageObject, ChatMessageCell chatMessageCell, String newMessage) {
        if (TextUtils.isEmpty(messageObject.messageOwner.message)) {
            setMessageCaption(messageObject, chatMessageCell.getCurrentMessagesGroup(), newMessage);
            messageObject.forceUpdate = true;
        } else {
            messageObject.messageOwner.message = newMessage;
            if (messageObject.caption != null) {
                messageObject.caption = null;
                messageObject.generateCaption();
                messageObject.forceUpdate = true;
            }
        }
        messageObject.applyNewText();
        messageObject.resetLayout();
        chatMessageCell.requestLayout();
        chatMessageCell.invalidate();
    }

    public static void addMessageContent(MessageObject messageObject, String addMessage) {
        if (TextUtils.isEmpty(messageObject.messageOwner.message)) {
            setMessageCaption(messageObject, null, addMessage);
            messageObject.forceUpdate = true;
        } else {
            messageObject.messageOwner.message = messageObject.messageOwner.message + addMessage;
            if (messageObject.caption != null) {
                messageObject.caption = null;
                messageObject.generateCaption();
                messageObject.forceUpdate = true;
            }
        }
        messageObject.applyNewText();
        messageObject.resetLayout();
    }

    private static void setMessageCaption(MessageObject messageObject, MessageObject.GroupedMessages group, CharSequence newCaption) {
        if (group == null) {
            messageObject.caption = newCaption;
            return;
        }
        int size = group.messages.size();
        for (int i = 0; i < size; i++) {
            MessageObject messageObject2 = group.messages.get(i);
            if (messageObject2.caption != null) {
                messageObject2.caption = newCaption;
                messageObject2.forceUpdate = true;
                messageObject2.applyNewText();
                messageObject2.resetLayout();
                return;
            }
        }
    }

    public static void showTranslateDialog(Context context, String query) {
        showTranslateDialog(context, query, !TextUtils.isEmpty(lastLangSelection) ? lastLangSelection : null, null);
    }

    public static void showTranslateDialog(Context context, String query, TranslateCallBack translateCallBack) {
        showTranslateDialog(context, query, !TextUtils.isEmpty(lastLangSelection) ? lastLangSelection : null, translateCallBack);
    }

    public static class SearchSettingsOnCloud {
        private int classGuid;
        private int currentAccount;
        private SearchSettingsOnCloudDelegate delegate;
        private int lastReqId;
        private Runnable searchRunnable;
        private int searchesInProgress;
        public ArrayList<MessageObject> globalSearch = new ArrayList<>();
        private ArrayList<MessageObject> searchResult = new ArrayList<>();
        private int reqId = 0;

        public interface SearchSettingsOnCloudDelegate {
            void onCompleted(ArrayList<MessageObject> list);
        }

        public SearchSettingsOnCloud(BaseFragment baseFragment, SearchSettingsOnCloudDelegate delegate) {
            this.classGuid = baseFragment.getClassGuid();
            this.currentAccount = baseFragment.getCurrentAccount();
            this.delegate = delegate;
            queryServerSearch(".data", 0, baseFragment.getUserConfig().clientUserId);
        }

        public void queryServerSearch(final String query, final int max_id, long did) {
            int i = (int) did;
            if (i == 0) {
                return;
            }
            if (this.reqId != 0) {
                ConnectionsManager.getInstance(UserConfig.selectedAccount).cancelRequest(this.reqId, true);
                this.reqId = 0;
                this.searchesInProgress--;
            }
            if (query == null || query.length() == 0) {
                this.globalSearch.clear();
                this.lastReqId = 0;
                return;
            }
            TLRPC.TL_messages_search tL_messages_search = new TLRPC.TL_messages_search();
            tL_messages_search.limit = 10;
            tL_messages_search.offset_id = max_id;
            tL_messages_search.filter = new TLRPC.TL_inputMessagesFilterDocument();
            tL_messages_search.q = query;
            TLRPC.InputPeer inputPeer = MessagesController.getInstance(this.currentAccount).getInputPeer(i);
            tL_messages_search.peer = inputPeer;
            if (inputPeer == null) {
                return;
            }
            final int i2 = this.lastReqId + 1;
            this.lastReqId = i2;
            this.searchesInProgress++;
            this.reqId = ConnectionsManager.getInstance(this.currentAccount).sendRequest(tL_messages_search, new RequestDelegate() {
                @Override
                public final void run(TLObject tLObject, TLRPC.TL_error tL_error) {
                    PlusUtils.SearchSettingsOnCloud.this.lambda$queryServerSearch$1(max_id, i2, tLObject, tL_error);
                }
            }, 2);
            ConnectionsManager.getInstance(this.currentAccount).bindRequestToGuid(this.reqId, this.classGuid);
        }

        public void lambda$queryServerSearch$1(int i, final int i2, TLObject tLObject, TLRPC.TL_error tL_error) {
            final ArrayList arrayList = new ArrayList();
            if (tL_error == null) {
                TLRPC.messages_Messages messages_messages = (TLRPC.messages_Messages) tLObject;
                for (int i3 = 0; i3 < messages_messages.messages.size(); i3++) {
                    TLRPC.Message message = messages_messages.messages.get(i3);
                    if (i == 0 || message.id <= i) {
                        MessageObject messageObject = new MessageObject(this.currentAccount, message, false, true);
                        if (messageObject.getDocumentName().endsWith(".data")) {
                            arrayList.add(messageObject);
                        }
                    }
                }
            }
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    PlusUtils.SearchSettingsOnCloud.this.lambda$queryServerSearch$0(i2, arrayList);
                }
            });
        }

        public void lambda$queryServerSearch$0(int i, ArrayList arrayList) {
            if (this.reqId != 0) {
                if (i == this.lastReqId) {
                    this.globalSearch = arrayList;
                    this.searchesInProgress--;
                    SearchSettingsOnCloudDelegate searchSettingsOnCloudDelegate = this.delegate;
                    if (searchSettingsOnCloudDelegate != null) {
                        searchSettingsOnCloudDelegate.onCompleted(arrayList);
                    }
                }
                this.reqId = 0;
            }
        }

        public void search(final String query) {
            Runnable runnable = this.searchRunnable;
            if (runnable != null) {
                AndroidUtilities.cancelRunOnUIThread(runnable);
                this.searchRunnable = null;
            }
            if (TextUtils.isEmpty(query)) {
                if (this.searchResult.isEmpty() && this.globalSearch.isEmpty() && this.searchesInProgress == 0) {
                    return;
                }
                this.searchResult.clear();
                this.globalSearch.clear();
                if (this.reqId != 0) {
                    ConnectionsManager.getInstance(this.currentAccount).cancelRequest(this.reqId, true);
                    this.reqId = 0;
                    this.searchesInProgress--;
                    return;
                }
                return;
            }
            Runnable runnable2 = new Runnable() {
                @Override
                public final void run() {
                    PlusUtils.SearchSettingsOnCloud.this.lambda$search$2(query);
                }
            };
            this.searchRunnable = runnable2;
            AndroidUtilities.runOnUIThread(runnable2, 300L);
        }

        public void lambda$search$2(String str) {
            queryServerSearch(str, 0, UserConfig.getInstance(this.currentAccount).clientUserId);
        }
    }

    public static class restoreAsyncTask extends AsyncTask<File, Void, Void> {
        private RestoreAsyncTaskDelegate delegate;
        private File[] files = new File[7];

        public interface RestoreAsyncTaskDelegate {
            void onError(String error);

            void onRestart();
        }

        public restoreAsyncTask(RestoreAsyncTaskDelegate delegate) {
            this.delegate = delegate;
        }

        @Override
        public Void doInBackground(File... data) {
            String str = ApplicationLoader.applicationContext.getCacheDir().getAbsolutePath() + "/";
            this.files[0] = new File(str + "plus");
            this.files[1] = new File(str + "plus1");
            this.files[2] = new File(str + "plus2");
            this.files[3] = new File(str + "plusconfig");
            this.files[4] = new File(str + "theme");
            this.files[5] = new File(str + "categories");
            this.files[6] = new File(str + "mark");
            try {
                new ZipManager().unzip(data[0], str);
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                RestoreAsyncTaskDelegate restoreAsyncTaskDelegate = this.delegate;
                if (restoreAsyncTaskDelegate == null) {
                    return null;
                }
                restoreAsyncTaskDelegate.onError(e.getMessage());
                return null;
            }
        }

        @Override
        public void onPostExecute(Void aVoid) {
            if (this.files[3].exists()) {
                Utilities.loadPrefFromCache("plusconfig", "plusconfig", true);
            }
            if (this.files[4].exists()) {
                Utilities.loadPrefFromCache("theme", "theme", true);
            }
            boolean exists = this.files[5].exists();
            Object obj = BuildConfig.APP_CENTER_HASH;
            if (exists) {
                StringBuilder sb = new StringBuilder();
                sb.append("categories");
                int i = UserConfig.selectedAccount;
                sb.append(i != 0 ? Integer.valueOf(i) : BuildConfig.APP_CENTER_HASH);
                Utilities.loadPrefFromCache("categories", sb.toString(), true);
            }
            if (this.files[6].exists()) {
                StringBuilder sb2 = new StringBuilder();
                sb2.append("mark");
                int i2 = UserConfig.selectedAccount;
                if (i2 != 0) {
                    obj = Integer.valueOf(i2);
                }
                sb2.append(obj);
                Utilities.loadPrefFromCache("mark", sb2.toString(), true);
            }
            if (this.files[0].exists() && this.files[1].exists() && this.files[2].exists()) {
                if (Utilities.loadDBFromCache("plus", "plus", true) == 4 && Utilities.loadDBFromCache("plus1", "plus-shm", true) == 4 && Utilities.loadDBFromCache("plus2", "plus-wal", true) == 4) {
                    RestoreAsyncTaskDelegate restoreAsyncTaskDelegate = this.delegate;
                    if (restoreAsyncTaskDelegate != null) {
                        restoreAsyncTaskDelegate.onRestart();
                        return;
                    } else {
                        Utilities.restartApp();
                        return;
                    }
                }
                return;
            }
            RestoreAsyncTaskDelegate restoreAsyncTaskDelegate2 = this.delegate;
            if (restoreAsyncTaskDelegate2 != null) {
                restoreAsyncTaskDelegate2.onError(LocaleController.formatString("ErrorOccurred", R.string.ErrorOccurred, new Object[0]));
            }
        }
    }

    public static class ZipManager {
        private static final int BUFFER_SIZE = 8192;
        private boolean delete = true;

        public void zip(String[] _files, String zipFileName) {
            try {
                ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
                byte[] bArr = new byte[8192];
                for (int i = 0; i < _files.length; i++) {
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(_files[i]), 8192);
                    zipOutputStream.putNextEntry(new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1)));
                    while (true) {
                        int read = bufferedInputStream.read(bArr, 0, 8192);
                        if (read == -1) {
                            break;
                        } else {
                            zipOutputStream.write(bArr, 0, read);
                        }
                    }
                    bufferedInputStream.close();
                    if (this.delete) {
                        File file = new File(_files[i]);
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                }
                zipOutputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void unzip(File zipfile, String _targetLocation) throws Exception {
            ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile())));
            while (true) {
                try {
                    ZipEntry nextEntry = zipInputStream.getNextEntry();
                    if (nextEntry == null) {
                        return;
                    }
                    File file = new File(_targetLocation, nextEntry.getName());
                    if (nextEntry.isDirectory()) {
                        file.mkdirs();
                    } else {
                        file.getCanonicalPath().startsWith(_targetLocation);
                        file.getParentFile().mkdirs();
                        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                        try {
                            byte[] bArr = new byte[8192];
                            while (true) {
                                int read = zipInputStream.read(bArr);
                                if (-1 != read) {
                                    bufferedOutputStream.write(bArr, 0, read);
                                } else {
                                    try {
                                        break;
                                    } catch (IOException e) {
                                        file.delete();
                                        throw e;
                                    }
                                }
                            }
                            bufferedOutputStream.close();
                        } finally {
                        }
                    }
                } finally {
                    zipInputStream.close();
                }
            }
        }
    }

    public static class LoadAllChats implements NotificationCenter.NotificationCenterDelegate, DialogInterface.OnCancelListener {
        private static boolean dialogsDidLoad;
        private int count;
        private int currentAccount;
        private LoadAllChatsDelegate delegate;
        private Runnable dismissProgressRunnable;
        private boolean forceResetDialogs;
        private int loadSize;
        private MessagesController messagesController;
        private boolean progressCancelled;
        private AlertDialog progressDialog;
        private int totalChatsCount;
        private int loadChatQ = Theme.plusChatsToLoad;
        private int folderId = 0;
        private boolean fromCache = true;
        private boolean showProgress = false;

        public interface LoadAllChatsDelegate {
            void onCancel();

            void onCompleted();
        }

        public LoadAllChats(Context context) {
            load(context);
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            this.progressCancelled = true;
            dismissProgress();
            LoadAllChatsDelegate loadAllChatsDelegate = this.delegate;
            if (loadAllChatsDelegate != null) {
                loadAllChatsDelegate.onCancel();
            }
        }

        public void load(Context context) {
            int i = UserConfig.selectedAccount;
            this.currentAccount = i;
            this.messagesController = MessagesController.getInstance(i);
            NotificationCenter.getInstance(this.currentAccount).addObserver(this, NotificationCenter.dialogsNeedReload);
            AlertDialog alertDialog = new AlertDialog(context, 3);
            this.progressDialog = alertDialog;
            alertDialog.setCanceledOnTouchOutside(false);
            this.progressDialog.setCancelable(true);
            this.progressDialog.setOnCancelListener(this);
            if ((this.fromCache || !this.messagesController.isServerDialogsEndReached(this.folderId)) && !dialogsDidLoad) {
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        LoadAllChats.this.progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
                        LoadAllChats.this.progressDialog.show();
                        LoadAllChats.this.messagesController.loadDialogs(LoadAllChats.this.folderId, -1, LoadAllChats.this.loadChatQ, LoadAllChats.this.fromCache);
                        if (LoadAllChats.this.forceResetDialogs) {
                            return;
                        }
                        LoadAllChats.dialogsDidLoad = true;
                    }
                }, 100L);
            } else {
                loadAll();
            }
        }

        public void setLoadAllChatsDelegateDelegate(LoadAllChatsDelegate loadAllChatsDelegate) {
            this.delegate = loadAllChatsDelegate;
        }

        private void loadAll() {
            this.totalChatsCount = this.messagesController.getDialogs(this.folderId).size();
            LoadAllChatsDelegate loadAllChatsDelegate = this.delegate;
            if (loadAllChatsDelegate != null) {
                loadAllChatsDelegate.onCompleted();
            }
            finish();
        }

        public void finish() {
            NotificationCenter.getInstance(this.currentAccount).removeObserver(this, NotificationCenter.dialogsNeedReload);
        }

        public void didReceivedNotification(int id, int account, Object... args) {
            if (id == NotificationCenter.dialogsNeedReload) {
                if (!MessagesController.getInstance(this.currentAccount).getDialogs(this.folderId).isEmpty()) {
                    if (MessagesController.getInstance(this.currentAccount).isLoadingDialogs(this.folderId)) {
                        return;
                    }
                    if ((this.fromCache || !this.messagesController.isServerDialogsEndReached(this.folderId)) && !this.progressCancelled) {
                        int size = MessagesController.getInstance(this.currentAccount).getDialogs(this.folderId).size();
                        double d = this.loadChatQ;
                        double ceil = Math.ceil(size / r4);
                        Double.isNaN(d);
                        this.count = (int) (d * ceil);
                        if (this.loadSize < size) {
                            this.loadSize = size;
                            AlertDialog alertDialog = this.progressDialog;
                            if (alertDialog != null && this.showProgress) {
                                alertDialog.setMessage(LocaleController.getString("Loading", R.string.Loading) + " " + this.count);
                            }
                            this.messagesController.loadDialogs(this.folderId, -1, this.loadChatQ, this.fromCache);
                            Runnable runnable = this.dismissProgressRunnable;
                            if (runnable != null) {
                                AndroidUtilities.cancelRunOnUIThread(runnable);
                            }
                            Runnable runnable2 = new Runnable() {
                                @Override
                                public void run() {
                                    if (LoadAllChats.this.dismissProgressRunnable != this) {
                                        return;
                                    }
                                    LoadAllChats.this.completeTask();
                                }
                            };
                            this.dismissProgressRunnable = runnable2;
                            AndroidUtilities.runOnUIThread(runnable2, 150L);
                            return;
                        }
                        return;
                    }
                    completeTask();
                    return;
                }
                completeTask();
            }
        }

        public void completeTask() {
            dismissProgress();
            loadAll();
        }

        private void dismissProgress() {
            if (this.dismissProgressRunnable != null) {
                this.dismissProgressRunnable = null;
            }
            AlertDialog alertDialog = this.progressDialog;
            if (alertDialog != null) {
                alertDialog.dismiss();
                this.progressDialog = null;
            }
            finish();
        }
    }

    public static void checkCacheSize(final Activity activity) {
        Utilities.globalQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$checkCacheSize$33(activity);
            }
        }, 2000L);
    }

    public static void lambda$checkCacheSize$33(final Activity activity) {
        long j;
        long j2;
        File file;
        long blockSize;
        long availableBlocks;
        try {
            SharedPreferences globalMainSettings = MessagesController.getGlobalMainSettings();
            if (Math.abs(globalMainSettings.getLong("last_cache_check", 0L) - System.currentTimeMillis()) < 864000000) {
                return;
            }
            long directorySize = getDirectorySize(FileLoader.checkDirectory(4), 0);
            long directorySize2 = getDirectorySize(FileLoader.checkDirectory(0), 0);
            long directorySize3 = getDirectorySize(FileLoader.checkDirectory(2), 0);
            long directorySize4 = getDirectorySize(FileLoader.checkDirectory(3), 1);
            long directorySize5 = getDirectorySize(FileLoader.checkDirectory(3), 2);
            long directorySize6 = getDirectorySize(new File(FileLoader.checkDirectory(4), "acache"), 0);
            long directorySize7 = getDirectorySize(FileLoader.checkDirectory(7), 0);
            File externalFilesDir = ApplicationLoader.applicationContext.getExternalFilesDir(null);
            long j3 = -1;
            if (externalFilesDir != null) {
                j2 = getDirectorySize(new File(externalFilesDir.getAbsolutePath() + "/logs"), 0);
                j = getDirectorySize(new File(externalFilesDir.getAbsolutePath() + "/Download"), 0);
            } else {
                j = -1;
                j2 = -1;
            }
            final long directorySize8 = directorySize + directorySize3 + getDirectorySize(FileLoader.checkDirectory(1), 0) + directorySize2 + directorySize4 + directorySize5 + directorySize6 + directorySize7 + j2 + j;
            if (Build.VERSION.SDK_INT >= 19) {
                ArrayList rootDirs = AndroidUtilities.getRootDirs();
                file = (File) rootDirs.get(0);
                file.getAbsolutePath();
                if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
                    int size = rootDirs.size();
                    for (int i = 0; i < size; i++) {
                        File file2 = (File) rootDirs.get(i);
                        if (file2.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
                            file = file2;
                            break;
                        }
                    }
                }
            } else {
                file = new File(SharedConfig.storageCacheDir);
            }
            try {
                StatFs statFs = new StatFs(file.getPath());
                int i2 = Build.VERSION.SDK_INT;
                if (i2 >= 18) {
                    blockSize = statFs.getBlockSizeLong();
                } else {
                    blockSize = statFs.getBlockSize();
                }
                if (i2 >= 18) {
                    availableBlocks = statFs.getAvailableBlocksLong();
                } else {
                    availableBlocks = statFs.getAvailableBlocks();
                }
                j3 = availableBlocks * blockSize;
            } catch (Exception e) {
                FileLog.e(e);
            }
            final long j4 = j3;
            if (directorySize8 / 1073741824 <= 5 || j4 / 1073741824 > 1) {
                return;
            }
            globalMainSettings.edit().putLong("last_cache_check", System.currentTimeMillis()).apply();
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public final void run() {
                    PlusUtils.lambda$checkCacheSize$32(activity, directorySize8, j4);
                }
            });
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }

    public static void lambda$checkCacheSize$32(Activity activity, long j, long j2) {
        try {
            AlertsCreator.createHighCacheSizeDialog((LaunchActivity) activity, j, j2).show();
        } catch (Throwable unused) {
        }
    }

    private static long getDirectorySize(File dir, int documentsMusicType) {
        if (dir == null) {
            return 0L;
        }
        if (dir.isDirectory()) {
            return Utilities.getDirSize(dir.getAbsolutePath(), documentsMusicType, false);
        }
        if (dir.isFile()) {
            return 0 + dir.length();
        }
        return 0L;
    }

    public static File getStoragePath() {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        if (Build.VERSION.SDK_INT < 19 || TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
            return externalStorageDirectory;
        }
        ArrayList rootDirs = AndroidUtilities.getRootDirs();
        int size = rootDirs.size();
        for (int i = 0; i < size; i++) {
            File file = (File) rootDirs.get(i);
            if (file.getAbsolutePath().startsWith(SharedConfig.storageCacheDir)) {
                return file;
            }
        }
        return externalStorageDirectory;
    }

    public static void getStoragePaths(BaseFragment fragment, final GetStoragePathsDelegate delegate) {
        String str;
        final AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
        builder.setTitle(LocaleController.getString("StoragePath", R.string.StoragePath));
        LinearLayout linearLayout = new LinearLayout(fragment.getParentActivity());
        linearLayout.setOrientation(1);
        builder.setView(linearLayout);
        final ArrayList rootDirs = AndroidUtilities.getRootDirs();
        String absolutePath = ((File) rootDirs.get(0)).getAbsolutePath();
        if (!TextUtils.isEmpty(SharedConfig.storageCacheDir)) {
            int size = rootDirs.size();
            for (int i = 0; i < size; i++) {
                String absolutePath2 = ((File) rootDirs.get(i)).getAbsolutePath();
                if (absolutePath2.startsWith(SharedConfig.storageCacheDir)) {
                    str = absolutePath2;
                    break;
                }
            }
        }
        str = absolutePath;
        int size2 = rootDirs.size();
        for (int i2 = 0; i2 < size2; i2++) {
            final String absolutePath3 = ((File) rootDirs.get(i2)).getAbsolutePath();
            final RadioColorCell radioColorCell = new RadioColorCell(fragment.getParentActivity());
            radioColorCell.setPadding(AndroidUtilities.dp(4.0f), 0, AndroidUtilities.dp(4.0f), 0);
            radioColorCell.setTag(Integer.valueOf(i2));
            radioColorCell.setCheckColor(Theme.getColor(Theme.key_radioBackground), Theme.getColor(Theme.key_dialogRadioBackgroundChecked));
            radioColorCell.setTextAndValue(absolutePath3, absolutePath3.startsWith(str));
            linearLayout.addView(radioColorCell);
            radioColorCell.setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    PlusUtils.lambda$getStoragePaths$34(absolutePath3, rootDirs, radioColorCell, builder, delegate, view);
                }
            });
        }
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        fragment.showDialog(builder.create());
    }

    public static void lambda$getStoragePaths$34(String str, ArrayList arrayList, RadioColorCell radioColorCell, AlertDialog.Builder builder, GetStoragePathsDelegate getStoragePathsDelegate, View view) {
        SharedConfig.storageCacheDir = str;
        SharedConfig.saveConfig();
        if (!((File) arrayList.get(PlusSettings.getStorage())).getAbsolutePath().equals(str)) {
            if (radioColorCell.getTag() != null) {
                PlusSettings.setStorage(Integer.parseInt(radioColorCell.getTag().toString()));
            } else {
                PlusSettings.toggleStorage();
            }
        }
        ImageLoader.getInstance().checkMediaPaths();
        builder.getDismissRunnable().run();
        if (getStoragePathsDelegate != null) {
            getStoragePathsDelegate.onCompleted();
        }
    }

    public static boolean openOriginalReplyChat(BaseFragment fragment, MessageObject messageObject) {
        long j;
        Bundle bundle = new Bundle();
        try {
            TLRPC.Peer peer = messageObject.messageOwner.fwd_from.saved_from_peer;
            long j2 = peer.channel_id;
            if (j2 != 0) {
                bundle.putLong("chat_id", j2);
            } else {
                long j3 = peer.chat_id;
                if (j3 != 0) {
                    bundle.putLong("chat_id", j3);
                } else {
                    long j4 = peer.user_id;
                    if (j4 != 0) {
                        bundle.putLong("user_id", j4);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (messageObject.messageOwner.fwd_from == null) {
            j = messageObject.getChatId();
        } else {
            j = -messageObject.getFromChatId();
        }
        if (j != 0) {
            bundle.putLong(j <= 0 ? "chat_id" : "user_id", -j);
        }
        bundle.putInt("message_id", messageObject.messageOwner.fwd_from.saved_from_msg_id);
        if (!MessagesController.getInstance(UserConfig.selectedAccount).checkCanOpenChat(bundle, fragment)) {
            return false;
        }
        fragment.presentFragment(new ChatActivity(bundle));
        return true;
    }

    public static void openExternalStoragePermission(Context context, boolean toast) {
        boolean isExternalStorageManager = Build.VERSION.SDK_INT >= 30 ? Environment.isExternalStorageManager() : false;
        if (BuildVars.NO_SCOPED_STORAGE || isExternalStorageManager) {
            if (isExternalStorageManager && toast) {
                showToast("Access to external storage is enabled");
                return;
            }
            return;
        }
        context.startActivity(new Intent("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", Uri.parse("package:" + ApplicationLoader.getApplicationId())));
    }

    public static void askForExternalStoragePermission(final Context context, boolean toast) {
        if (verifyInstallerId()) {
            return;
        }
        boolean isExternalStorageManager = Build.VERSION.SDK_INT >= 30 ? Environment.isExternalStorageManager() : false;
        if (toast && SharedConfig.dontAskManageStorage) {
            SharedConfig.dontAskManageStorage = false;
        }
        if (!BuildVars.NO_SCOPED_STORAGE && !SharedConfig.dontAskManageStorage && !isExternalStorageManager) {
            if (isAskForStorageDialogVisible) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTopImage(R.drawable.doc_big, Theme.usePlusTheme ? Theme.defColor : Theme.getColor(Theme.key_dialogTopBackground));
            builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ManageAllFilesRational3", R.string.ManageAllFilesRational3)));
            final TextCheckBoxCell textCheckBoxCell = new TextCheckBoxCell(context, true, true);
            textCheckBoxCell.setTextAndCheck(LocaleController.getString("DontAskAgain", R.string.DontAskAgain), false, false);
            textCheckBoxCell.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textCheckBoxCell.setChecked(!r2.isChecked());
                }
            });
            builder.setView(textCheckBoxCell);
            builder.setPositiveButton(LocaleController.getString("Allow", R.string.Allow), new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.lambda$askForExternalStoragePermission$35(context, dialogInterface, i);
                }
            });
            builder.setNegativeButton(LocaleController.getString("No", R.string.No), new DialogInterface.OnClickListener() {
                @Override
                public final void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.lambda$askForExternalStoragePermission$36(textCheckBoxCell, dialogInterface, i);
                }
            });
            builder.show();
            isAskForStorageDialogVisible = true;
            return;
        }
        isAskForStorageDialogVisible = false;
        if (isExternalStorageManager && toast) {
            showToast("Access to external storage is enabled");
        }
    }

    public static void lambda$askForExternalStoragePermission$35(Context context, DialogInterface dialogInterface, int i) {
        context.startActivity(new Intent("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", Uri.parse("package:" + ApplicationLoader.getApplicationId())));
        isAskForStorageDialogVisible = false;
    }

    public static void lambda$askForExternalStoragePermission$36(TextCheckBoxCell textCheckBoxCell, DialogInterface dialogInterface, int i) {
        if (textCheckBoxCell.isChecked()) {
            SharedConfig.setDontAskManageStorage(true);
        }
        isAskForStorageDialogVisible = false;
    }

    public static void setStickerSize(BaseFragment fragment, final ActionDelegate delegate) {
        AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getParentActivity());
        builder.setTitle(LocaleController.getString("StickerSize", R.string.StickerSize));
        final NumberPicker numberPicker = new NumberPicker(fragment.getParentActivity());
        numberPicker.setMinValue(2);
        numberPicker.setMaxValue(25);
        numberPicker.setValue((int) PlusSettings.stickerSize);
        builder.setView(numberPicker);
        builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                PlusSettings.stickerSize = NumberPicker.this.getValue() * 1.0f;
                SharedPreferences.Editor edit = ApplicationLoader.applicationContext.getSharedPreferences("plusconfig", 0).edit();
                edit.putFloat("stickerSize", PlusSettings.stickerSize);
                edit.apply();
                ActionDelegate actionDelegate = delegate;
                if (actionDelegate != null) {
                    actionDelegate.onCompleted();
                }
            }
        });
        fragment.showDialog(builder.create());
    }

    public static boolean setValue(Context context, String url, int type) {
        Uri parse = Uri.parse(url);
        return setValue(context, type, parse.getQueryParameter("key"), parse.getQueryParameter("value"), parse.getQueryParameter("force"));
    }

    public static boolean setValue(final Context context, final int type, final String key, final String value, String force) {
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
            if (!TextUtils.isEmpty(force) && force.equals("true")) {
                setValue(type, key, value);
                if (context instanceof LaunchActivity) {
                    ((LaunchActivity) context).rebuildAllFragments(true);
                }
                return false;
            }
            if (context == null) {
                return false;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(LocaleController.getString("ApplyTheme", R.string.ApplyTheme));
            builder.setMessage(key + ": " + value);
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    PlusUtils.setValue(type, key, value);
                    LaunchActivity launchActivity = context;
                    if (launchActivity instanceof LaunchActivity) {
                        launchActivity.rebuildAllFragments(true);
                    }
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
            builder.show();
        }
        return false;
    }

    public static boolean setValue(int type, String key, String value) {
        SharedPreferences globalMainSettings;
        if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
            return false;
        }
        int i = UserConfig.selectedAccount;
        if (type == 2) {
            Context context = ApplicationLoader.applicationContext;
            StringBuilder sb = new StringBuilder();
            sb.append("userconfing");
            sb.append(i == 0 ? BuildConfig.APP_CENTER_HASH : Integer.valueOf(i));
            globalMainSettings = context.getSharedPreferences(sb.toString(), 0);
        } else if (type == 1) {
            globalMainSettings = MessagesController.getMainSettings(i);
        } else {
            globalMainSettings = MessagesController.getGlobalMainSettings();
        }
        SharedPreferences.Editor edit = globalMainSettings.edit();
        if (value.equals("true") || value.equals("false")) {
            edit.putBoolean(key, Boolean.parseBoolean(value));
        } else if (isInteger(value)) {
            edit.putInt(key, Integer.parseInt(value));
        } else if (value.equals("reset")) {
            edit.remove(key);
        } else {
            edit.putString(key, value);
        }
        edit.apply();
        AndroidUtilities.runOnUIThread(new Runnable() {
            @Override
            public final void run() {
                Utilities.restartApp();
            }
        }, 500L);
        return true;
    }

    public static boolean setPlusValue(Context context, String url) {
        Uri parse = Uri.parse(url);
        return setPlusValue(context, parse.getQueryParameter("key"), parse.getQueryParameter("value"), parse.getQueryParameter("force"));
    }

    public static boolean setPlusValue(String key, String value) {
        boolean z = false;
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
            SharedPreferences.Editor edit = ApplicationLoader.applicationContext.getSharedPreferences("plusconfig", 0).edit();
            if (value.equals("true") || value.equals("false")) {
                if (key.equals("deleteHiddenPasscode")) {
                    if (value.equals("true")) {
                        PlusSettings.deleteHiddenPasscode();
                        Utilities.restartApp();
                        return true;
                    }
                } else if (key.equals("cleanupDatabase")) {
                    if (value.equals("true")) {
                        cleanDb(false);
                        return true;
                    }
                } else if (key.equals("resetChats") && value.equals("true")) {
                    MessagesController.getInstance(UserConfig.selectedAccount).forceResetDialogs();
                }
                edit.putBoolean(key, Boolean.parseBoolean(value));
            } else if (isInteger(value)) {
                if (key.equals("maxaccount")) {
                    try {
                        if (Integer.parseInt(value) <= 10) {
                            UserConfig.setMaxAccountCount(Integer.parseInt(value));
                            Utilities.restartApp();
                            return true;
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                } else if (key.equals("cleanupDatabase")) {
                    try {
                        MessagesStorage.getInstance(Integer.parseInt(value)).cleanup(false);
                        Utilities.restartApp();
                        return true;
                    } catch (NumberFormatException e2) {
                        e2.printStackTrace();
                    }
                }
                edit.putInt(key, Integer.parseInt(value));
            } else if (value.equals("reset")) {
                edit.remove(key);
            } else {
                if (key.equals("resetplus")) {
                    edit.clear();
                }
                edit.apply();
                Theme.updatePlusPrefs();
            }
            z = true;
            edit.apply();
            Theme.updatePlusPrefs();
        }
        return z;
    }

    public static void cleanDbDialog(Activity parentActivity, boolean restart) {
        AlertDialog.Builder builder = new AlertDialog.Builder(parentActivity);
        builder.setTitle("Clean up database");
        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new AnonymousClass13(restart, parentActivity));
        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
        builder.show();
    }

    public class AnonymousClass13 implements DialogInterface.OnClickListener {
        public final Activity val$parentActivity;
        public final boolean val$restart;

        public AnonymousClass13(final boolean val$restart, final Activity val$parentActivity) {
            this.val$restart = val$restart;
            this.val$parentActivity = val$parentActivity;
        }

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (this.val$restart) {
                PlusUtils.cleanDb(false);
                MessagesController.getMainSettings(UserConfig.selectedAccount).edit().putBoolean("localFiltersLoaded_", false).apply();
                AlertDialog.Builder builder = new AlertDialog.Builder(this.val$parentActivity);
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setMessage(LocaleController.getString("AppWillRestart", R.string.AppWillRestart));
                String upperCase = LocaleController.getString("OK", R.string.OK).toUpperCase();
                final Activity activity = this.val$parentActivity;
                builder.setPositiveButton(upperCase, new DialogInterface.OnClickListener() {
                    @Override
                    public final void onClick(DialogInterface dialogInterface2, int i2) {
                        PlusUtils.restartApp(activity);
                    }
                });
                final Activity activity2 = this.val$parentActivity;
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public final void onCancel(DialogInterface dialogInterface2) {
                        PlusUtils.restartApp(activity2);
                    }
                });
                builder.show();
                return;
            }
            PlusUtils.cleanDb(false);
        }
    }

    public static void cleanDb(boolean restart) {
        MessagesStorage.getInstance(UserConfig.selectedAccount).cleanup(false);
        MessagesController.getInstance(UserConfig.selectedAccount).forceResetDialogs();
        MessagesController.getInstance(UserConfig.selectedAccount).loadRemoteFilters(true);
        if (restart) {
            AndroidUtilities.runOnUIThread(new Runnable() {
                @Override
                public void run() {
                    Utilities.restartApp();
                }
            }, 500L);
        }
    }

    public static void restartApp(Activity activity) {
        Intent launchIntentForPackage = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
        activity.finishAffinity();
        activity.startActivity(launchIntentForPackage);
        System.exit(0);
    }

    public static void sendLogs(Activity parentActivity, boolean last) {
        sendLogs(parentActivity, last, false);
    }

    public static void sendLogs(final Activity parentActivity, final boolean last, final boolean onlyLogcat) {
        if (parentActivity == null) {
            return;
        }
        final AlertDialog alertDialog = new AlertDialog(parentActivity, 3);
        alertDialog.show();
        Utilities.globalQueue.postRunnable(new Runnable() {
            @Override
            public final void run() {
                PlusUtils.lambda$sendLogs$40(last, onlyLogcat, alertDialog, parentActivity);
            }
        });
    }

    public static void lambda$sendLogs$40(boolean r19, boolean r20, final org.telegram.ui.ActionBar.AlertDialog r21, final android.app.Activity r22) {
        throw new UnsupportedOperationException("Method not decompiled: org.telegram.messenger.PlusUtils.lambda$sendLogs$40(boolean, boolean, org.telegram.ui.ActionBar.AlertDialog, android.app.Activity):void");
    }

    public static void lambda$sendLogs$38(AlertDialog alertDialog, boolean[] zArr, Activity activity, File file) {
        Uri fromFile;
        try {
            alertDialog.dismiss();
        } catch (Exception unused) {
        }
        if (!zArr[0]) {
            if (activity != null) {
                Toast.makeText(activity, LocaleController.getString("ErrorOccurred", R.string.ErrorOccurred), 0).show();
                return;
            }
            return;
        }
        int i = Build.VERSION.SDK_INT;
        if (i >= 24) {
            fromFile = FileProvider.getUriForFile(activity, ApplicationLoader.getApplicationId() + ".provider", file);
        } else {
            fromFile = Uri.fromFile(file);
        }
        Intent intent = new Intent("android.intent.action.SEND");
        if (i >= 24) {
            intent.addFlags(1);
        }
        intent.setType("message/rfc822");
        intent.putExtra("android.intent.extra.EMAIL", BuildConfig.APP_CENTER_HASH);
        intent.putExtra("android.intent.extra.SUBJECT", "Logs from " + LocaleController.getInstance().formatterStats.format(System.currentTimeMillis()));
        intent.putExtra("android.intent.extra.STREAM", fromFile);
        if (activity != null) {
            try {
                activity.startActivityForResult(Intent.createChooser(intent, "Select email application."), 500);
            } catch (Exception e) {
                FileLog.e(e);
            }
        }
    }

    public static void lambda$sendLogs$39(AlertDialog alertDialog, Activity activity) {
        try {
            alertDialog.dismiss();
        } catch (Exception unused) {
        }
        if (activity != null) {
            Toast.makeText(activity, LocaleController.getString("SendLogsEmpty", R.string.SendLogsEmpty), 0).show();
        }
    }

    public static boolean setPlusValue(final Context context, final String key, final String value, String force) {
        if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
            if (!TextUtils.isEmpty(force) && force.equals("true")) {
                setPlusValue(key, value);
                if (context instanceof LaunchActivity) {
                    ((LaunchActivity) context).rebuildAllFragments(true);
                }
                return false;
            }
            if (context == null) {
                return false;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(LocaleController.getString("ApplyTheme", R.string.ApplyTheme));
            builder.setMessage(key + ": " + value);
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (key.equals("changeHiddenPasscode")) {
                        SharedConfig.hiddenPasscodeHash = BuildConfig.APP_CENTER_HASH;
                        SharedConfig.saveConfig();
                        context.presentFragment(new PasscodeActivity(5));
                    } else {
                        PlusUtils.setPlusValue(key, value);
                        LaunchActivity launchActivity = context;
                        if (launchActivity instanceof LaunchActivity) {
                            launchActivity.rebuildAllFragments(true);
                        }
                    }
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
            builder.show();
        }
        return false;
    }

    public static boolean isInteger2(String s) {
        if (s.isEmpty()) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            if (i == 0 && s.charAt(i) == '-') {
                if (s.length() == 1) {
                    return false;
                }
            } else if (Character.digit(s.charAt(i), 10) < 0) {
                return false;
            }
        }
        return true;
    }

    public static boolean isInteger(String s) {
        Scanner scanner = new Scanner(s.trim());
        if (!scanner.hasNextInt(10)) {
            return false;
        }
        scanner.nextInt(10);
        return !scanner.hasNext();
    }

    public static String getAppDownloadLink() {
        String str;
        if (verifyInstallerId()) {
            return "https://play.google.com/store/apps/details?id=org.telegram.plus";
        }
        try {
            int i = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0).versionCode % 10;
            if (i == 1) {
                str = "https://install.appcenter.ms/users/rafalense-70ux/apps/plus-release/distribution_groups/public";
            } else if (i == 8) {
                str = "https://install.appcenter.ms/users/rafalense-70ux/apps/plus/distribution_groups/all-users-of-plus";
            } else {
                if (i != 9) {
                    return "https://play.google.com/store/apps/details?id=org.telegram.plus";
                }
                str = "https://install.appcenter.ms/users/rafalense-70ux/apps/Plus-Messenger-beta";
            }
            return str;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "https://play.google.com/store/apps/details?id=org.telegram.plus";
        }
    }

    public static void applyEntities(ArrayList<TLRPC.MessageEntity> entities, SpannableStringBuilder stringBuilder) {
        applyEntities(entities, stringBuilder, 0);
    }

    public static void applyEntities(ArrayList<TLRPC.MessageEntity> entities, SpannableStringBuilder stringBuilder, int start) {
        Iterator<TLRPC.MessageEntity> it = entities.iterator();
        while (it.hasNext()) {
            TLRPC.MessageEntity next = it.next();
            int i = next.offset + start;
            next.offset = i;
            if (i <= stringBuilder.length()) {
                if (next instanceof TLRPC.TL_inputMessageEntityMentionName) {
                    URLSpan uRLSpan = new URLSpan("tg://user?id=" + ((TLRPC.TL_inputMessageEntityMentionName) next).user_id.user_id);
                    int i2 = next.offset;
                    stringBuilder.setSpan(uRLSpan, i2, next.length + i2, 33);
                } else if (next instanceof TLRPC.TL_messageEntityMentionName) {
                    URLSpan uRLSpan2 = new URLSpan("tg://user?id=" + ((TLRPC.TL_messageEntityMentionName) next).user_id);
                    int i3 = next.offset;
                    stringBuilder.setSpan(uRLSpan2, i3, next.length + i3, 33);
                } else if ((next instanceof TLRPC.TL_messageEntityCode) || (next instanceof TLRPC.TL_messageEntityPre)) {
                    TypefaceSpan typefaceSpan = new TypefaceSpan("monospace");
                    int i4 = next.offset;
                    stringBuilder.setSpan(typefaceSpan, i4, next.length + i4, 33);
                } else if (next instanceof TLRPC.TL_messageEntityBold) {
                    StyleSpan styleSpan = new StyleSpan(1);
                    int i5 = next.offset;
                    stringBuilder.setSpan(styleSpan, i5, next.length + i5, 33);
                } else if (next instanceof TLRPC.TL_messageEntityItalic) {
                    StyleSpan styleSpan2 = new StyleSpan(2);
                    int i6 = next.offset;
                    stringBuilder.setSpan(styleSpan2, i6, next.length + i6, 33);
                } else if (next instanceof TLRPC.TL_messageEntityStrike) {
                    StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
                    int i7 = next.offset;
                    stringBuilder.setSpan(strikethroughSpan, i7, next.length + i7, 33);
                } else if (next instanceof TLRPC.TL_messageEntityUnderline) {
                    UnderlineSpan underlineSpan = new UnderlineSpan();
                    int i8 = next.offset;
                    stringBuilder.setSpan(underlineSpan, i8, next.length + i8, 33);
                } else if (next instanceof TLRPC.TL_messageEntityTextUrl) {
                    URLSpan uRLSpan3 = new URLSpan(next.url);
                    int i9 = next.offset;
                    stringBuilder.setSpan(uRLSpan3, i9, next.length + i9, 33);
                } else if (next instanceof TLRPC.TL_messageEntitySpoiler) {
                    BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Theme.getColor(Theme.key_chats_archivePullDownBackground));
                    int i10 = next.offset;
                    stringBuilder.setSpan(backgroundColorSpan, i10, next.length + i10, 33);
                }
            }
        }
    }

    public static void getEntities(Spanned spannable, ArrayList<TLRPC.MessageEntity> entities) {
        for (CharacterStyle characterStyle : (CharacterStyle[]) spannable.getSpans(0, spannable.length(), CharacterStyle.class)) {
            if ((spannable.getSpanFlags(characterStyle) & 256) == 0) {
                int spanStart = spannable.getSpanStart(characterStyle);
                int spanEnd = spannable.getSpanEnd(characterStyle);
                if (characterStyle instanceof URLSpan) {
                    String url = ((URLSpan) characterStyle).getURL();
                    if (url != null) {
                        if (url.startsWith("tg://user?id=")) {
                            String replace = url.replace("tg://user?id=", BuildConfig.APP_CENTER_HASH);
                            TLRPC.TL_inputMessageEntityMentionName tL_inputMessageEntityMentionName = new TLRPC.TL_inputMessageEntityMentionName();
                            TLRPC.InputUser inputUser = MessagesController.getInstance(UserConfig.selectedAccount).getInputUser(Utilities.parseLong(replace).longValue());
                            tL_inputMessageEntityMentionName.user_id = inputUser;
                            if (inputUser != null) {
                                tL_inputMessageEntityMentionName.offset = spanStart;
                                int i = spanEnd - spanStart;
                                tL_inputMessageEntityMentionName.length = i;
                                if (spannable.charAt((spanStart + i) - 1) == ' ') {
                                    tL_inputMessageEntityMentionName.length--;
                                }
                                entities.add(tL_inputMessageEntityMentionName);
                            }
                        } else {
                            TLRPC.MessageEntity tL_messageEntityTextUrl = new TLRPC.TL_messageEntityTextUrl();
                            tL_messageEntityTextUrl.offset = spanStart;
                            tL_messageEntityTextUrl.length = spanEnd - spanStart;
                            tL_messageEntityTextUrl.url = url;
                            entities.add(tL_messageEntityTextUrl);
                        }
                    }
                } else if (characterStyle instanceof StyleSpan) {
                    int style = ((StyleSpan) characterStyle).getStyle();
                    if (style == 1) {
                        entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityBold(), spanStart, spanEnd));
                    } else if (style == 2) {
                        entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityItalic(), spanStart, spanEnd));
                    } else if (style == 3) {
                        entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityBold(), spanStart, spanEnd));
                        entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityItalic(), spanStart, spanEnd));
                    }
                } else if (characterStyle instanceof TypefaceSpan) {
                    if ("monospace".equals(((TypefaceSpan) characterStyle).getFamily())) {
                        LocaleSpan[] localeSpanArr = (LocaleSpan[]) spannable.getSpans(spanStart, spanEnd, LocaleSpan.class);
                        if (localeSpanArr != null && localeSpanArr.length > 0 && localeSpanArr[0].getLocale() != null && "ng".equalsIgnoreCase(localeSpanArr[0].getLocale().getCountry())) {
                            TLRPC.MessageEntity tL_messageEntityPre = new TLRPC.TL_messageEntityPre();
                            tL_messageEntityPre.offset = spanStart;
                            tL_messageEntityPre.length = spanEnd - spanStart;
                            tL_messageEntityPre.language = localeSpanArr[0].getLocale().getLanguage();
                            entities.add(tL_messageEntityPre);
                        } else {
                            entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityCode(), spanStart, spanEnd));
                        }
                    }
                } else if (characterStyle instanceof UnderlineSpan) {
                    entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityUnderline(), spanStart, spanEnd));
                } else if (characterStyle instanceof StrikethroughSpan) {
                    entities.add(setEntityStartEnd(new TLRPC.TL_messageEntityStrike(), spanStart, spanEnd));
                } else if (characterStyle instanceof BackgroundColorSpan) {
                    entities.add(setEntityStartEnd(new TLRPC.TL_messageEntitySpoiler(), spanStart, spanEnd));
                }
            }
        }
    }

    public static boolean isEnabled() {
        return PlusSettings.keepFormatting;
    }

    private static TLRPC.MessageEntity setEntityStartEnd(TLRPC.MessageEntity entity, int spanStart, int spanEnd) {
        entity.offset = spanStart;
        entity.length = spanEnd - spanStart;
        return entity;
    }

    public static void addStyleToText(final Style style, EditTextCaption editTextCaption, final EditTextCaption.EditTextCaptionDelegate delegate, final int start, final int end) {
        String string;
        String string2;
        String str;
        Style style2;
        Style style3;
        final Editable text = editTextCaption.getText();
        Theme.ResourcesProvider resourcesProvider = editTextCaption.resourcesProvider;
        Context context = editTextCaption.getContext();
        Style style4 = Style.MENTION;
        if (style == style4 || style == Style.URL || style == (style3 = Style.MONO)) {
            if (style == style4) {
                string = LocaleController.getString("CreateMention", R.string.CreateMention);
                string2 = "ID";
                str = BuildConfig.APP_CENTER_HASH;
            } else {
                string = LocaleController.getString("CreateLink", R.string.CreateLink);
                string2 = LocaleController.getString("URL", R.string.URL);
                str = "https://";
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context, resourcesProvider);
            builder.setTitle(string);
            final EditTextBoldCursor editTextBoldCursor = new EditTextBoldCursor(context) {
                @Override
                public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                    super.onMeasure(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(64.0f), 1073741824));
                }
            };
            if (style == style4) {
                editTextBoldCursor.setInputType(2);
            }
            editTextBoldCursor.setTextSize(1, 18.0f);
            editTextBoldCursor.setTextColor(Theme.getColor(Theme.key_dialogTextBlack, resourcesProvider));
            editTextBoldCursor.setText(str);
            editTextBoldCursor.setHintText(string2);
            editTextBoldCursor.setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader, resourcesProvider));
            editTextBoldCursor.setSingleLine(true);
            editTextBoldCursor.setFocusable(true);
            editTextBoldCursor.setTransformHintToHeader(true);
            editTextBoldCursor.setBackground(null);
            editTextBoldCursor.setLineColors(Theme.getColor(Theme.key_dialogInputField), Theme.getColor(Theme.key_dialogInputFieldActivated), Theme.getColor(Theme.key_text_RedBold));
            editTextBoldCursor.setImeOptions(6);
            editTextBoldCursor.requestFocus();
            editTextBoldCursor.setPadding(0, 0, 0, 0);
            builder.setView(editTextBoldCursor);
            CharacterStyle[] characterStyleArr = (CharacterStyle[]) text.getSpans(start, end, CharacterStyle.class);
            if (characterStyleArr != null && characterStyleArr.length > 0) {
                int length = characterStyleArr.length;
                int i = 0;
                while (true) {
                    if (i >= length) {
                        break;
                    }
                    CharacterStyle characterStyle = characterStyleArr[i];
                    if ((characterStyle instanceof URLSpan) && (style == (style2 = Style.MENTION) || style == Style.URL)) {
                        String url = ((URLSpan) characterStyle).getURL();
                        if (!TextUtils.isEmpty(url)) {
                            if (style == style2) {
                                if (url.startsWith("tg://user?id=")) {
                                    editTextBoldCursor.setText(url.replace("tg://user?id=", BuildConfig.APP_CENTER_HASH));
                                    break;
                                }
                            } else {
                                editTextBoldCursor.setText(url);
                                break;
                            }
                        } else {
                            continue;
                        }
                        i++;
                    } else {
                        if ((characterStyle instanceof LocaleSpan) && style == Style.MONO) {
                            Locale locale = ((LocaleSpan) characterStyle).getLocale();
                            String language = (locale == null || !"ng".equalsIgnoreCase(locale.getCountry())) ? null : locale.getLanguage();
                            if (!TextUtils.isEmpty(language)) {
                                editTextBoldCursor.setText(language);
                                break;
                            }
                        }
                        i++;
                    }
                }
            }
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), (DialogInterface.OnClickListener) null);
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), (DialogInterface.OnClickListener) null);
            final AlertDialog show = builder.show();
            show.getButton(-1).setOnClickListener(new View.OnClickListener() {
                @Override
                public final void onClick(View view) {
                    PlusUtils.lambda$addStyleToText$41(EditTextBoldCursor.this, style, text, start, end, delegate, show, view);
                }
            });
            show.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public final void onShow(DialogInterface dialogInterface) {
                    PlusUtils.lambda$addStyleToText$42(EditTextBoldCursor.this, dialogInterface);
                }
            });
            ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) editTextBoldCursor.getLayoutParams();
            if (marginLayoutParams != null) {
                if (marginLayoutParams instanceof FrameLayout.LayoutParams) {
                    ((FrameLayout.LayoutParams) marginLayoutParams).gravity = 1;
                }
                int dp = AndroidUtilities.dp(24.0f);
                marginLayoutParams.leftMargin = dp;
                marginLayoutParams.rightMargin = dp;
                marginLayoutParams.height = AndroidUtilities.dp(36.0f);
                editTextBoldCursor.setLayoutParams(marginLayoutParams);
            }
            editTextBoldCursor.setSelection(0, editTextBoldCursor.getText().length());
            return;
        }
        if (style == Style.BOLD) {
            text.setSpan(new StyleSpan(1), start, end, 33);
        } else if (style == Style.ITALIC) {
            text.setSpan(new StyleSpan(2), start, end, 33);
        } else if (style == Style.STRIKE) {
            text.setSpan(new StrikethroughSpan(), start, end, 33);
        } else if (style == Style.UNDERLINE) {
            text.setSpan(new UnderlineSpan(), start, end, 33);
        } else if (style == Style.SPOILER) {
            text.setSpan(new BackgroundColorSpan(Theme.getColor(Theme.key_chats_archivePullDownBackground)), start, end, 33);
        } else if (style == style3) {
            clearSpan(text, start, end);
            text.setSpan(new TypefaceSpan("monospace"), start, end, 33);
        } else if (style == Style.REGULAR) {
            clearSpan(text, start, end);
        }
        if (delegate != null) {
            delegate.onSpansChanged();
        }
    }

    public static void lambda$addStyleToText$41(EditTextBoldCursor editTextBoldCursor, Style style, Editable editable, int i, int i2, EditTextCaption.EditTextCaptionDelegate editTextCaptionDelegate, AlertDialog alertDialog, View view) {
        URLSpan[] uRLSpanArr;
        String obj = editTextBoldCursor.getText().toString();
        Style style2 = Style.URL;
        if (style == style2 && !LinkifyPort.WEB_URL.matcher(obj).matches()) {
            AndroidUtilities.shakeView(editTextBoldCursor);
            return;
        }
        if ((style == Style.MENTION || style == style2) && (uRLSpanArr = (URLSpan[]) editable.getSpans(i, i2, URLSpan.class)) != null && uRLSpanArr.length > 0) {
            for (URLSpan uRLSpan : uRLSpanArr) {
                int spanStart = editable.getSpanStart(uRLSpan);
                int spanEnd = editable.getSpanEnd(uRLSpan);
                editable.removeSpan(uRLSpan);
                if (spanStart < i) {
                    editable.setSpan(uRLSpan, spanStart, i, 33);
                }
                if (spanEnd > i2) {
                    editable.setSpan(uRLSpan, i2, spanEnd, 33);
                }
            }
        }
        try {
            if (style == Style.MENTION) {
                editable.setSpan(new URLSpan("tg://user?id=" + obj), i, i2, 33);
            } else if (style == Style.MONO) {
                clearSpan(editable, i, i2);
                editable.setSpan(new TypefaceSpan("monospace"), i, i2, 33);
            } else {
                editable.setSpan(new URLSpan(obj), i, i2, 33);
            }
        } catch (Exception unused) {
        }
        if (editTextCaptionDelegate != null) {
            editTextCaptionDelegate.onSpansChanged();
        }
        alertDialog.dismiss();
    }

    public static void lambda$addStyleToText$42(EditTextBoldCursor editTextBoldCursor, DialogInterface dialogInterface) {
        editTextBoldCursor.requestFocus();
        AndroidUtilities.showKeyboard(editTextBoldCursor);
    }

    private static void clearSpan(Editable editable, int start, int end) {
        CharacterStyle[] characterStyleArr = (CharacterStyle[]) editable.getSpans(start, end, CharacterStyle.class);
        if (characterStyleArr == null || characterStyleArr.length <= 0) {
            return;
        }
        for (CharacterStyle characterStyle : characterStyleArr) {
            editable.removeSpan(characterStyle);
        }
    }

    public static CharSequence commonizeSpans(CharSequence text) {
        if (!PlusSettings.keepFormatting || !(text instanceof Spanned)) {
            return text;
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text);
        for (CharacterStyle characterStyle : (CharacterStyle[]) spannableStringBuilder.getSpans(0, spannableStringBuilder.length(), CharacterStyle.class)) {
            int spanStart = spannableStringBuilder.getSpanStart(characterStyle);
            int spanEnd = spannableStringBuilder.getSpanEnd(characterStyle);
            if (characterStyle instanceof URLSpanMono) {
                ((URLSpanMono) characterStyle).getStyle();
                spannableStringBuilder.setSpan(new TypefaceSpan("monospace"), spanStart, spanEnd, 33);
            } else if (characterStyle instanceof URLSpanUserMention) {
                spannableStringBuilder.setSpan(new URLSpan("tg://user?id=" + Long.parseLong(((URLSpanUserMention) characterStyle).getURL())), spanStart, spanEnd, 33);
            } else if (characterStyle instanceof URLSpanReplacement) {
                spannableStringBuilder.setSpan(new URLSpan(((URLSpanReplacement) characterStyle).getURL()), spanStart, spanEnd, 33);
            } else if (characterStyle instanceof TextStyleSpan) {
                int styleFlags = ((TextStyleSpan) characterStyle).getStyleFlags();
                if ((styleFlags & 1) > 0) {
                    spannableStringBuilder.setSpan(new StyleSpan(1), spanStart, spanEnd, 33);
                }
                if ((styleFlags & 2) > 0) {
                    spannableStringBuilder.setSpan(new StyleSpan(2), spanStart, spanEnd, 33);
                }
                if ((styleFlags & 16) > 0) {
                    spannableStringBuilder.setSpan(new UnderlineSpan(), spanStart, spanEnd, 33);
                }
                if ((styleFlags & 8) > 0) {
                    spannableStringBuilder.setSpan(new StrikethroughSpan(), spanStart, spanEnd, 33);
                }
                if ((styleFlags & 256) > 0) {
                    spannableStringBuilder.setSpan(new BackgroundColorSpan(Theme.getColor(Theme.key_chats_archivePullDownBackground)), spanStart, spanEnd, 33);
                }
            }
        }
        return spannableStringBuilder;
    }
}