导航菜单

页面标题

页面副标题

Rilo v2.0.21 - AgentBroadcastChatActivity.java 源代码

正在查看: Rilo v2.0.21 应用的 AgentBroadcastChatActivity.java JAVA 源代码文件

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


package app.callpe.ui.chat;

import android.R;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ShareCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import app.callpe.App;
import app.callpe.adapters.MessageAdapter;
import app.callpe.common.utils.AnimatorHelper;
import app.callpe.common.utils.CenterSmoothScroller;
import app.callpe.common.utils.Constants;
import app.callpe.common.utils.DateHelper;
import app.callpe.common.utils.GroupUtils;
import app.callpe.common.utils.Helper;
import app.callpe.common.utils.ImageHW;
import app.callpe.common.utils.ImageUtils;
import app.callpe.common.utils.RxBus;
import app.callpe.common.utils.custom.CustomLinearLayoutManager;
import app.callpe.common.utils.custom.RecyclerSectionItemDecoration;
import app.callpe.common.utils.file_helper.CompressFile;
import app.callpe.common.utils.file_helper.Files;
import app.callpe.common.utils.helper_functions.AudioRecorder;
import app.callpe.common.utils.helper_functions.DialogHelper;
import app.callpe.common.utils.helper_functions.Result;
import app.callpe.common.utils.interfaces.TwoWayEndlessAdapter;
import app.callpe.common.utils.popupkeyboardwidget.GridMenuAdapter;
import app.callpe.common.utils.popupkeyboardwidget.MenuEditText;
import app.callpe.common.utils.popupkeyboardwidget.SoftKeyBoardPopup;
import app.callpe.common.utils.sharedpref.PrefKeys;
import app.callpe.common.utils.sharedpref.SharedPref;
import app.callpe.data.model.APIError;
import app.callpe.data.model.AgentModel;
import app.callpe.data.model.DownloadStatus;
import app.callpe.data.model.ErrorHandler;
import app.callpe.data.model.GroupModel;
import app.callpe.data.model.GroupOfflineModel;
import app.callpe.data.model.IntentModel;
import app.callpe.data.model.LoginResponse;
import app.callpe.data.model.SuccessModel;
import app.callpe.databinding.ActivityTaskDetailBinding;
import app.callpe.databinding.ChatMessageInputBinding;
import app.callpe.db.LocalDB;
import app.callpe.db.dao.ChatDao;
import app.callpe.service.ApiService;
import app.callpe.service.FirebaseNotificationService;
import app.callpe.service.SyncResponse;
import app.callpe.service.SyncResponseEventType;
import app.callpe.service.SyncRxBus;
import app.callpe.ui.chat.AgentBroadcastChatActivity;
import app.callpe.ui.home.AgentHomeActivity;
import app.callpe.ui.home.BaseActivity;
import app.callpe.ui.home.HomeActivity;
import app.callpe.ui.misc.ImageShowActivity;
import com.abedelazizshe.lightcompressorlibrary.CompressionListener;
import com.abedelazizshe.lightcompressorlibrary.VideoCompressor;
import com.abedelazizshe.lightcompressorlibrary.VideoQuality;
import com.abedelazizshe.lightcompressorlibrary.config.AppSpecificStorageConfiguration;
import com.abedelazizshe.lightcompressorlibrary.config.Configuration;
import com.asynctaskcoffee.audiorecorder.worker.AudioRecordListener;
import com.bumptech.glide.Glide;
import com.devlomi.record_view.OnRecordListener;
import com.devlomi.record_view.RecordButton;
import com.devlomi.record_view.RecordPermissionHandler;
import com.devlomi.record_view.RecordView;
import com.downloader.Error;
import com.downloader.Progress;
import com.facebook.internal.FacebookRequestErrorClassification;
import com.facebook.internal.NativeProtocol;
import com.github.dhaval2404.imagepicker.ImagePicker;
import com.github.dhaval2404.imagepicker.provider.GalleryProvider;
import com.github.dhaval2404.imagepicker.util.GalleryFile;
import com.google.gson.Gson;
import com.vanniktech.emoji.EmojiPopup;
import in.onato.imageeditor.editor.EditorActivity;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.inject.Inject;
import kotlin.Unit;
import kotlin.jvm.functions.Function2;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber;

public class AgentBroadcastChatActivity extends BaseActivity<ActivityTaskDetailBinding> implements AudioRecordListener, MenuEditText.PopupListener, MessageAdapter.TaskItemAdapterClickListener, SoftKeyBoardPopup.PopMenuClick {
    public static final int DOC_CODE = 5000;
    public static final int REQUEST_PERMISSIONS = 200;
    private static final int REQUEST_VIDEO_CAPTURE = 1000;
    private static final long UPDATE_INTERVAL = 1500;
    public static long chatId = -1;
    private ActionMode actionMode;
    private ActionModeCallback actionModeCallback;
    private AlertDialog alertDialog;

    @Inject
    ApiService apiService;
    private AudioRecorder audioRecorder;

    @Inject
    ChatDao chatDao;
    private RecyclerView chatRecyclerView;
    private GroupViewModel chatViewModel;
    private CompositeDisposable disposable;
    public MenuEditText editText;
    EmojiPopup emojiPopup;
    private LoginResponse loginResponse;
    public SoftKeyBoardPopup menuKeyboard;
    private MessageAdapter messageAdapter;
    public View parentView;
    private ProgressDialog progressDialog;
    private RecordButton recordButton;
    private File recordFile;
    public ConstraintLayout rootView;

    @Inject
    RxBus rxBus;
    ChatMessageInputBinding viewMessageInputBinding;
    private String accountId = "";
    private boolean isAgent = false;
    private boolean isCurrentSender = false;
    private boolean adminOnly = false;
    private String[] permissions = {"android.permission.RECORD_AUDIO", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"};
    boolean permissionToRecordAccepted = false;
    private boolean isVisible = false;
    private String role = Constants.ROLE.AGENT.name();
    private Long currentPage = -1L;
    private Long bottomPage = -1L;
    private final int PAGE_SIZE = 50;
    private Long searchMessageId = -1L;
    private Long replyId = null;
    private String replyMessage = null;
    private String replyType = null;
    private String name = "";
    private final ArrayList<GroupModel> chatModelArrayList = new ArrayList<>();
    private final HashMap<Long, Long> idMapper = new HashMap<>();
    private ConcurrentHashMap<Uri, Float> progressMap = new ConcurrentHashMap<>();
    private AtomicInteger activeCompressions = new AtomicInteger(0);
    private Handler handler = new Handler(Looper.getMainLooper());
    private long lastUpdateTime = 0;
    private final BroadcastReceiver broadcastReceiver = new AnonymousClass9();

    public interface HandleResult {
        void onResult(File file);
    }

    public Context getContext() {
        return this;
    }

    private void handleForward() {
    }

    private void showPlacePicker() {
    }

    @Override
    public void onAudioClick(GroupModel chatModel, int position) {
    }

    @Override
    public void onInfoClick(GroupModel chatModel, int position) {
    }

    @Override
    public void onLocationClick(GroupModel chatModel, int position) {
    }

    @Override
    public void onReadyForRecord() {
    }

    @Override
    public void onRecordFailed(String errorMessage) {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 30) {
            this.permissions = new String[]{"android.permission.RECORD_AUDIO", "android.permission.CAMERA", "android.permission.READ_EXTERNAL_STORAGE"};
        } else {
            this.permissions = new String[]{"android.permission.RECORD_AUDIO", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE", "android.permission.CAMERA"};
        }
        ActivityCompat.requestPermissions(this, this.permissions, 200);
        this.viewMessageInputBinding = ChatMessageInputBinding.bind(((ActivityTaskDetailBinding) this.binding).getRoot());
        ((ActivityTaskDetailBinding) this.binding).chatLayout.setVisibility(8);
        chatId = SharedPref.getLong(getContext(), PrefKeys.AGENT_BROADCAST_CHAT_ID, -1L);
        if (savedInstanceState != null) {
            chatId = savedInstanceState.getLong("chatId");
            this.name = savedInstanceState.getString(FacebookRequestErrorClassification.KEY_NAME);
            this.accountId = savedInstanceState.getString("userId");
            this.isCurrentSender = savedInstanceState.getBoolean("isCurrentSender");
            this.adminOnly = savedInstanceState.getBoolean("adminOnly");
        }
        getUserId();
        getIntent();
        long j = SharedPref.getLong(getContext(), PrefKeys.AGENT_BROADCAST_CHAT_ID, 0L);
        chatId = j;
        if (j == -1) {
            onBackPressed();
        }
        setContentView(((ActivityTaskDetailBinding) this.binding).getRoot());
        this.actionModeCallback = new ActionModeCallback(this, null);
        this.chatViewModel = (GroupViewModel) new ViewModelProvider(this).get(GroupViewModel.class);
        if (chatId != -1) {
            clearNotificationCount();
        }
        this.rootView = ((ActivityTaskDetailBinding) this.binding).rootView;
        this.parentView = findViewById(R.id.content);
        this.editText = this.viewMessageInputBinding.messageInput;
        this.viewMessageInputBinding.camera.setVisibility(0);
        this.viewMessageInputBinding.emoji.setVisibility(0);
        this.viewMessageInputBinding.recordMessageBtn.setVisibility(0);
        ConstraintLayout constraintLayout = ((ActivityTaskDetailBinding) this.binding).chatLayout;
        this.editText.setPopupListener(this);
        this.menuKeyboard = new SoftKeyBoardPopup(this, this.rootView, this.editText, constraintLayout, this.viewMessageInputBinding.menuChatContainer, this, this);
        try {
            this.emojiPopup = new EmojiPopup(this.rootView, this.editText);
        } catch (Exception e) {
            Timber.e(e);
        }
        this.viewMessageInputBinding.menuChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m948lambda$onCreate$0$appcallpeuichatAgentBroadcastChatActivity(view);
            }
        });
        handleSearchIntent();
        setRecycler();
        setUpRecordView();
        setProgressDialog();
        getLoginResponse();
        if (!App.notificationAvailable) {
            getChatResponse(!this.chatViewModel.fromSearch, false);
        }
        getParticipantResponse();
        submitChatOnClick();
        onBackClick();
        setToolbar();
        setSwipeToRefresh();
        observerMessageText();
        observeSyncResponse();
        onReplyClose();
        onClick();
    }

    void m948lambda$onCreate$0$appcallpeuichatAgentBroadcastChatActivity(View view) {
        toggle();
    }

    private void getUserId() {
        String string = SharedPref.getString(getContext(), PrefKeys.ACCOUNT_ID);
        if (SharedPref.getString(getContext(), PrefKeys.USER_ROLE).equals(Constants.ROLE.AGENT.name())) {
            this.isAgent = true;
            this.role = Constants.ROLE.AGENT.name();
        } else {
            this.role = Constants.ROLE.USER.name();
        }
        this.accountId = string;
    }

    private void handleSearchIntent() {
        this.chatViewModel.messageId = Long.valueOf(getIntent().getLongExtra("messageId", -1L));
        if (this.chatViewModel.messageId.longValue() != -1) {
            this.idMapper.put(this.chatViewModel.messageId, this.chatViewModel.messageId);
            this.chatViewModel.fromSearch = true;
            this.searchMessageId = this.chatViewModel.messageId;
            if (getIntent().getStringExtra("query") != null) {
                this.chatViewModel.query = getIntent().getStringExtra("query");
            }
        }
    }

    private void setUpRecordView() {
        this.viewMessageInputBinding.menuChat.setVisibility(0);
        this.audioRecorder = new AudioRecorder();
        RecordView recordView = this.viewMessageInputBinding.recordView;
        recordView.setLessThanSecondAllowed(false);
        RecordButton recordButton = this.viewMessageInputBinding.recordMessageBtn;
        this.recordButton = recordButton;
        recordButton.setRecordView(recordView);
        recordView.setRecordPermissionHandler(new RecordPermissionHandler() {
            public final boolean isPermissionGranted() {
                return AgentBroadcastChatActivity.this.m957xc5aa114c();
            }
        });
        recordView.setOnRecordListener(new AnonymousClass1(recordView));
    }

    boolean m957xc5aa114c() {
        if (ContextCompat.checkSelfPermission(this, "android.permission.RECORD_AUDIO") == 0) {
            return true;
        }
        ActivityCompat.requestPermissions(this, new String[]{"android.permission.RECORD_AUDIO"}, 0);
        return false;
    }

    class AnonymousClass1 implements OnRecordListener {
        final RecordView val$recordView;

        public void onLock() {
        }

        AnonymousClass1(final RecordView val$recordView) {
            this.val$recordView = val$recordView;
        }

        public void onStart() {
            this.val$recordView.setBackground(ContextCompat.getDrawable(AgentBroadcastChatActivity.this.getContext(), 2131231768));
            new Handler().postDelayed(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass1.this.m959lambda$onStart$0$appcallpeuichatAgentBroadcastChatActivity$1();
                }
            }, 300L);
        }

        void m959lambda$onStart$0$appcallpeuichatAgentBroadcastChatActivity$1() {
            AgentBroadcastChatActivity.this.recordFile = new File(AgentBroadcastChatActivity.this.getContext().getExternalFilesDir(null).getAbsolutePath() + "/Recorder_" + UUID.randomUUID().toString() + ".m4a");
            try {
                AgentBroadcastChatActivity.this.audioRecorder.start(AgentBroadcastChatActivity.this.recordFile.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void onCancel() {
            Handler handler = new Handler();
            final RecordView recordView = this.val$recordView;
            handler.postDelayed(new Runnable() {
                @Override
                public final void run() {
                    recordView.setBackground((Drawable) null);
                }
            }, 500L);
            AgentBroadcastChatActivity.this.stopRecording(true);
        }

        public void onFinish(long recordTime, boolean limitReached) {
            this.val$recordView.setBackground((Drawable) null);
            Timber.e("record time %s", new Object[]{Long.valueOf(recordTime)});
            AgentBroadcastChatActivity.this.stopRecording(false);
            if (AgentBroadcastChatActivity.this.recordFile == null || AgentBroadcastChatActivity.this.recordFile.getPath().isEmpty()) {
                return;
            }
            AgentBroadcastChatActivity agentBroadcastChatActivity = AgentBroadcastChatActivity.this;
            agentBroadcastChatActivity.submitChatResponse(agentBroadcastChatActivity.recordFile.getPath(), Constants.CHAT_TYPE.AUDIO.name(), recordTime);
        }

        public void onLessThanSecond() {
            this.val$recordView.setBackground((Drawable) null);
            AgentBroadcastChatActivity.this.stopRecording(true);
        }
    }

    private void onReplyClose() {
        ((ActivityTaskDetailBinding) this.binding).replyClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m950x4479d781(view);
            }
        });
    }

    void m950x4479d781(View view) {
        this.replyId = null;
        this.replyMessage = null;
        this.replyType = null;
        AnimatorHelper.collapse(((ActivityTaskDetailBinding) this.binding).replyViewParent);
    }

    private void setRecycler() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailRefreshLayout.setEnabled(false);
        this.chatRecyclerView = ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView;
        CustomLinearLayoutManager customLinearLayoutManager = new CustomLinearLayoutManager(this);
        customLinearLayoutManager.setStackFromEnd(!this.chatViewModel.fromSearch);
        ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.setLayoutManager(customLinearLayoutManager);
        this.chatRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        this.chatRecyclerView.addItemDecoration(new RecyclerSectionItemDecoration(getResources().getDimensionPixelSize(2131167283), true, new RecyclerSectionItemDecoration.SectionCallback() {
            @Override
            public boolean isSection(int position) {
                try {
                    if (AgentBroadcastChatActivity.this.messageAdapter == null) {
                        return false;
                    }
                    if (position != 0) {
                        if (AgentBroadcastChatActivity.this.messageAdapter.getUserMessagesList().get(position).getCreationDate().equals(AgentBroadcastChatActivity.this.messageAdapter.getUserMessagesList().get(position - 1).getCreationDate())) {
                            return false;
                        }
                    }
                    return true;
                } catch (Exception unused) {
                    return false;
                }
            }

            @Override
            public CharSequence getSectionHeader(int position) {
                try {
                    return AgentBroadcastChatActivity.this.messageAdapter == null ? "" : AgentBroadcastChatActivity.this.messageAdapter.getUserMessagesList().get(position).getCreationDate().isEmpty() ? DateHelper.chatHeaderDate(DateHelper.getTodayDate(), "yyyy-MM-dd", AgentBroadcastChatActivity.this.getContext()) : DateHelper.chatHeaderDate(AgentBroadcastChatActivity.this.messageAdapter.getUserMessagesList().get(position).getCreationDate(), "yyyy-MM-dd", AgentBroadcastChatActivity.this.getContext());
                } catch (Exception unused) {
                    return "";
                }
            }
        }));
        this.chatRecyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public final void onLayoutChange(View view, int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
                AgentBroadcastChatActivity.this.m955xf232fb3d(view, i, i2, i3, i4, i5, i6, i7, i8);
            }
        });
        Timber.e("account id %s", new Object[]{this.accountId});
        if (this.accountId.isEmpty()) {
            Helper.INSTANCE.triggerRebirth(this);
        }
        MessageAdapter messageAdapter = new MessageAdapter(new ArrayList(), this, Long.valueOf(this.accountId), this);
        this.messageAdapter = messageAdapter;
        messageAdapter.role = this.role;
        this.messageAdapter.allowSelection = true;
        this.messageAdapter.downloadedAudio = false;
        this.messageAdapter.setDataContainer(new ArrayList());
        this.messageAdapter.setEndlessCallback(new TwoWayEndlessAdapter.Callback() {
            @Override
            public void onTopReached() {
                AgentBroadcastChatActivity.this.addItems(true);
                Timber.e("I am Top", new Object[0]);
            }

            @Override
            public void onBottomReached() {
                if (AgentBroadcastChatActivity.this.chatViewModel.fromSearch) {
                    AgentBroadcastChatActivity.this.addItems(false);
                }
                Timber.e("I am bottom", new Object[0]);
            }
        });
        this.chatRecyclerView.setAdapter(this.messageAdapter);
    }

    void m955xf232fb3d(View view, int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
        if (i4 < i8) {
            this.chatRecyclerView.postDelayed(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m954x7cb8d4fc();
                }
            }, 100L);
        }
    }

    void m954x7cb8d4fc() {
        try {
            if (isLastVisible()) {
                Timber.e("isLastVisible", new Object[0]);
                if (this.messageAdapter != null) {
                    this.chatRecyclerView.scrollToPosition(r0.getItemCount() - 1);
                }
            }
        } catch (Exception unused) {
        }
    }

    public void addItems(boolean isTop) {
        Timber.i("add items %s", new Object[]{this.currentPage});
        if (isTop) {
            MessageAdapter messageAdapter = this.messageAdapter;
            if ((messageAdapter != null && messageAdapter.getItemCount() == 1) || this.idMapper.containsKey(this.currentPage)) {
                return;
            }
            HashMap<Long, Long> hashMap = this.idMapper;
            Long l = this.currentPage;
            hashMap.put(l, l);
            Timber.i("add items after %s", new Object[]{this.currentPage});
        } else {
            MessageAdapter messageAdapter2 = this.messageAdapter;
            if ((messageAdapter2 != null && messageAdapter2.getItemCount() == 1) || this.idMapper.containsKey(this.bottomPage)) {
                return;
            }
            HashMap<Long, Long> hashMap2 = this.idMapper;
            Long l2 = this.bottomPage;
            hashMap2.put(l2, l2);
        }
        getChatResponse(false, isTop);
    }

    private void setToolbar() {
        try {
            ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.taskName.setText(getString(2131951662));
            ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.profile.setVisibility(0);
            ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.moreIcon.setVisibility(8);
            ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.callIcon.setVisibility(8);
            Glide.with(getContext()).load(2131230881).error(2131230886).into(((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.profile);
        } catch (Exception e) {
            Timber.e(e);
        }
    }

    private void setSwipeToRefresh() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            public final void onRefresh() {
                AgentBroadcastChatActivity.this.m956xf7d51545();
            }
        });
    }

    void m956xf7d51545() {
        releasePlayer();
        getChatResponse(true, false);
        ((ActivityTaskDetailBinding) this.binding).taskDetailRefreshLayout.setRefreshing(false);
    }

    public void setProgress(boolean isVisible) {
        if (isVisible) {
            this.viewMessageInputBinding.recordMessageBtn.setEnabled(false);
            ((ActivityTaskDetailBinding) this.binding).taskDetailProgress.setVisibility(0);
        } else {
            this.viewMessageInputBinding.recordMessageBtn.setEnabled(true);
            ((ActivityTaskDetailBinding) this.binding).taskDetailProgress.setVisibility(8);
        }
    }

    private void submitChatOnClick() {
        this.viewMessageInputBinding.recordMessageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m958xf5d047f7(view);
            }
        });
    }

    void m958xf5d047f7(View view) {
        submitChat();
    }

    private void onClick() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.toolbarParent.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m945lambda$onClick$7$appcallpeuichatAgentBroadcastChatActivity(view);
            }
        });
        this.viewMessageInputBinding.camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m946lambda$onClick$8$appcallpeuichatAgentBroadcastChatActivity(view);
            }
        });
        this.viewMessageInputBinding.emoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m947lambda$onClick$9$appcallpeuichatAgentBroadcastChatActivity(view);
            }
        });
    }

    void m945lambda$onClick$7$appcallpeuichatAgentBroadcastChatActivity(View view) {
        startActivity(new Intent((Context) this, (Class<?>) ParticipantAgentActivity.class));
    }

    void m946lambda$onClick$8$appcallpeuichatAgentBroadcastChatActivity(View view) {
        openCamera();
    }

    void m947lambda$onClick$9$appcallpeuichatAgentBroadcastChatActivity(View view) {
        EmojiPopup emojiPopup = this.emojiPopup;
        if (emojiPopup != null) {
            if (emojiPopup.isShowing()) {
                this.emojiPopup.dismiss();
                showEmojiIcon(true);
            } else {
                showEmojiIcon(false);
                this.emojiPopup.show();
            }
        }
    }

    private void submitChat() {
        if (this.viewMessageInputBinding.messageInput.getText() == null || this.viewMessageInputBinding.messageInput.getText().toString().isEmpty()) {
            return;
        }
        String trim = this.viewMessageInputBinding.messageInput.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            return;
        }
        submitChatResponse(trim, Constants.CHAT_TYPE.TEXT.toString(), 0L);
    }

    public void showParticipantsName(ArrayList<AgentModel> participantModelArrayList) {
        String string = SharedPref.getString(this, PrefKeys.ACCOUNT_ID);
        if (participantModelArrayList != null && participantModelArrayList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < participantModelArrayList.size(); i++) {
                try {
                    AgentModel agentModel = participantModelArrayList.get(i);
                    if (i < 7) {
                        if (i == 0) {
                            if (String.valueOf(agentModel.getId()).equals(string)) {
                                sb.append(getString(2131953101));
                            } else if (agentModel.getName() != null) {
                                sb.append(agentModel.getName().trim());
                                sb.append(",");
                            }
                        } else if (String.valueOf(agentModel.getId()).equals(string)) {
                            sb.append(getString(2131953101));
                        } else if (agentModel.getName() != null) {
                            sb.append(",");
                            sb.append(agentModel.getName().trim());
                        }
                    }
                } catch (Exception e) {
                    Timber.e(e);
                }
                if (i >= 8) {
                    break;
                }
            }
            ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.userStatus.setText(sb);
            return;
        }
        ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.userStatus.setText(getString(2131953101));
    }

    private void getParticipantResponse() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.userStatus.setVisibility(0);
        ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.userStatus.setText(2131952946);
        this.apiService.getAllAgentParticipants().enqueue(new AnonymousClass5());
    }

    class AnonymousClass5 implements Callback<ArrayList<AgentModel>> {
        public void onFailure(Call<ArrayList<AgentModel>> call, Throwable t) {
        }

        AnonymousClass5() {
        }

        public void onResponse(Call<ArrayList<AgentModel>> call, final Response<ArrayList<AgentModel>> response) {
            Timber.e("onResponse: Participant Response %s", new Object[]{response.raw()});
            if (!response.isSuccessful() || response.body() == null) {
                return;
            }
            new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass5.this.m960x887d8723(response);
                }
            }, 1000L);
        }

        void m960x887d8723(Response response) {
            AgentBroadcastChatActivity.this.showParticipantsName((ArrayList) response.body());
        }
    }

    public void submitChatResponse(String str, String str2, long j) {
        int i;
        String todayDateWithTime;
        Long valueOf;
        Long valueOf2;
        Long l;
        String str3;
        String str4;
        String str5;
        String str6;
        int i2 = 0;
        i2 = 0;
        i2 = 0;
        try {
        } catch (Exception e) {
            e = e;
            i = i2;
        }
        try {
            if (!str2.equals(Constants.CHAT_TYPE.TEXT.name()) && !str2.equals(Constants.CHAT_TYPE.LOCATION.name())) {
                if (str2.equals(Constants.CHAT_TYPE.IMAGE.name()) || str2.equals(Constants.CHAT_TYPE.VIDEO.name()) || str2.equals(Constants.CHAT_TYPE.AUDIO.name()) || str2.equals(Constants.CHAT_TYPE.DOCUMENT.name())) {
                    Timber.e("file path %s", new Object[]{str});
                    uploadOffline(str, str2, j);
                }
                return;
            }
            this.chatViewModel.addGroupModel(new GroupOfflineModel(str, false, null, todayDateWithTime, valueOf, valueOf2, l, str3, str4, str5, false, null, str6, str2, null, this.role, false, true, UUID.randomUUID().toString(), 0L));
            this.viewMessageInputBinding.messageInput.setText("");
            this.viewMessageInputBinding.messageInput.setHint("Type a message");
            i2 = str6;
            return;
        } catch (Exception e2) {
            e = e2;
            i = 0;
            Timber.e(e, "Error: ", new Object[i]);
            return;
        }
        todayDateWithTime = DateHelper.getTodayDateWithTime("yyyy-MM-dd HH:mm:ss", true);
        valueOf = Long.valueOf(chatId);
        valueOf2 = Long.valueOf(Long.parseLong(this.accountId));
        l = this.replyId;
        str3 = this.replyMessage;
        str4 = this.replyType;
        str5 = this.name;
        str6 = this.name;
    }

    private void deleteMessageResponse(GroupModel model) {
        ActionMode actionMode = this.actionMode;
        if (actionMode != null && this.actionModeCallback != null) {
            actionMode.finish();
            this.actionModeCallback.onDestroyActionMode(this.actionMode);
        }
        if (model.isRetry().booleanValue()) {
            this.chatViewModel.deleteMessage(model);
        } else {
            this.apiService.deleteMessage(String.valueOf(model.getId())).enqueue(new Callback<SuccessModel>() {
                public void onResponse(Call<SuccessModel> call, Response<SuccessModel> response) {
                    try {
                        AgentBroadcastChatActivity.this.setProgress(false);
                        Timber.d("onResponse: %s", new Object[]{response.raw()});
                        if (response.isSuccessful()) {
                            if (response.body() != null) {
                                AgentBroadcastChatActivity.this.setProgress(false);
                                AgentBroadcastChatActivity.this.reset();
                                AgentBroadcastChatActivity.this.getChatResponse(true, false);
                            }
                        } else {
                            try {
                                APIError parseError = ErrorHandler.parseError(response);
                                Toast.makeText(this, AgentBroadcastChatActivity.this.getString(2131952996) + ": " + parseError.getReason(), 0).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } catch (Exception unused) {
                    }
                }

                public void onFailure(Call<SuccessModel> call, Throwable t) {
                    AgentBroadcastChatActivity.this.setProgress(false);
                    Timber.e("onFailure: %s", new Object[]{t.getMessage()});
                    Helper.noNetworkToast(this, t);
                }
            });
        }
    }

    public void getChatResponse(final boolean canScroll, final boolean isTop) {
        Timber.d("getChatResponse: task id %s", new Object[]{Long.valueOf(chatId)});
        setProgress(true);
        this.chatViewModel.getChatList(this.accountId, this.role, String.valueOf(chatId), isTop ? this.currentPage : this.bottomPage, 50, "AGENT_BROADCAST").observe(this, new Observer() {
            public final void onChanged(Object obj) {
                AgentBroadcastChatActivity.this.m929xeeb1b03a(canScroll, isTop, (Result) obj);
            }
        });
    }

    void m929xeeb1b03a(boolean z, boolean z2, Result result) {
        if (result instanceof Result.Success) {
            setProgress(false);
            List list = (List) ((Result.Success) result).data;
            if (list == null || list.isEmpty()) {
                return;
            }
            if (this.chatViewModel.fromSearch) {
                if (this.currentPage.longValue() != -1) {
                    Timber.i("Page Current %s", new Object[]{this.currentPage});
                    Timber.i("Page Current Id %s", new Object[]{((GroupModel) list.get(list.size() - 1)).getId()});
                    this.currentPage = Long.valueOf(Math.min(((GroupModel) list.get(list.size() - 1)).getId().longValue(), this.currentPage.longValue()));
                } else {
                    this.currentPage = ((GroupModel) list.get(list.size() - 1)).getId();
                }
                Timber.i("Page Top %s", new Object[]{this.currentPage});
                Timber.i("Page Bottom %s", new Object[]{this.bottomPage});
                Timber.i("can scroll %s", new Object[]{Boolean.valueOf(z)});
            } else {
                this.currentPage = ((GroupModel) list.get(list.size() - 1)).getId();
            }
            Timber.i("current page %s", new Object[]{this.currentPage});
            this.chatModelArrayList.clear();
            this.chatModelArrayList.addAll(list);
            Collections.reverse(this.chatModelArrayList);
            MessageAdapter messageAdapter = this.messageAdapter;
            if (messageAdapter != null) {
                if (z2) {
                    messageAdapter.addItemsAtTop(this.chatModelArrayList);
                } else {
                    messageAdapter.addItemsAtBottom(this.chatModelArrayList);
                }
                this.messageAdapter.addAll(this.chatModelArrayList);
                if (this.chatViewModel.groupMessage != null) {
                    this.messageAdapter.addItem(this.chatViewModel.groupMessage);
                    this.chatViewModel.groupMessage = null;
                    this.chatRecyclerView.scrollToPosition(this.chatModelArrayList.size() - 1);
                }
            }
            try {
                if (this.searchMessageId.longValue() != -1) {
                    scrollAndHighlightBackground(this.searchMessageId.longValue());
                    this.searchMessageId = -1L;
                } else if (z) {
                    this.chatRecyclerView.scrollToPosition(this.chatModelArrayList.size() - 1);
                }
                return;
            } catch (Exception unused) {
                return;
            }
        }
        if (result instanceof Result.Error) {
            try {
                setProgress(false);
                Toast.makeText((Context) this, (CharSequence) ("" + ((Result.Error) result).exception), 0).show();
                return;
            } catch (Exception e) {
                Timber.e(e);
                return;
            }
        }
        if (result instanceof Result.Failure) {
            try {
                setProgress(false);
                Toast.makeText((Context) this, (CharSequence) ("" + ((Result.Failure) result).failure.getMessage()), 0).show();
            } catch (Exception e2) {
                Timber.e(e2);
            }
        }
    }

    public void notifyCall() {
        this.apiService.getAgentChatMessageList(String.valueOf(chatId), -1L, 1).enqueue(new Callback<ArrayList<GroupModel>>() {
            public void onFailure(Call<ArrayList<GroupModel>> call, Throwable t) {
            }

            public void onResponse(Call<ArrayList<GroupModel>> call, Response<ArrayList<GroupModel>> response) {
                Timber.e("onResponse: notifyCall %s", new Object[]{response.raw()});
            }
        });
    }

    private void uploadOffline(String filePath, String type, long recordTime) {
        GroupOfflineModel groupOfflineModel;
        FileOutputStream fileOutputStream;
        if (type.equals(Constants.CHAT_TYPE.VIDEO.name())) {
            Bitmap createVideoThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, 1);
            String str = getContext().getExternalFilesDir(Environment.DIRECTORY_DCIM) + "/video_" + System.currentTimeMillis() + ".jpg";
            Timber.e("uploadImage: bitmap file %s", new Object[]{str});
            try {
                fileOutputStream = new FileOutputStream(str);
            } catch (Exception e) {
                Toast.makeText(getContext(), 2131952996, 0).show();
                e.printStackTrace();
            }
            try {
                createVideoThumbnail.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
                fileOutputStream.close();
                this.chatViewModel.addGroupModel(new GroupOfflineModel(filePath, false, null, DateHelper.getTodayDateWithTime("yyyy-MM-dd HH:mm:ss", true), Long.valueOf(chatId), Long.valueOf(Long.parseLong(this.accountId)), this.replyId, this.replyMessage, this.replyType, this.name, false, null, this.name, type, str, this.role, false, true, UUID.randomUUID().toString(), Long.valueOf(recordTime)));
            } finally {
            }
        } else {
            GroupOfflineModel groupOfflineModel2 = new GroupOfflineModel(filePath, false, null, DateHelper.getTodayDateWithTime("yyyy-MM-dd HH:mm:ss", true), Long.valueOf(chatId), Long.valueOf(Long.parseLong(this.accountId)), this.replyId, this.replyMessage, this.replyType, this.name, false, null, this.name, type, null, this.role, false, true, UUID.randomUUID().toString(), Long.valueOf(recordTime / 1000));
            if (type.equals(Constants.CHAT_TYPE.DOCUMENT.name())) {
                try {
                    if (filePath.contains(".pdf")) {
                        String convertBitmapToFile = Helper.convertBitmapToFile(filePath, getContext());
                        if (convertBitmapToFile != null) {
                            groupOfflineModel = groupOfflineModel2;
                            try {
                                groupOfflineModel.setThumbnail(convertBitmapToFile);
                                groupOfflineModel.setFileName(new File(filePath).getName());
                            } catch (Exception e2) {
                                e = e2;
                                Timber.e(e);
                                this.chatViewModel.addGroupModel(groupOfflineModel);
                            }
                        }
                    }
                    groupOfflineModel = groupOfflineModel2;
                    groupOfflineModel.setFileName(new File(filePath).getName());
                } catch (Exception e3) {
                    e = e3;
                    groupOfflineModel = groupOfflineModel2;
                }
            } else {
                groupOfflineModel = groupOfflineModel2;
                if (type.equals(Constants.CHAT_TYPE.IMAGE.name())) {
                    try {
                        ImageHW imageHeightWidth = ImageUtils.INSTANCE.getImageHeightWidth(new File(filePath), 260.0f, 320.0f);
                        Integer valueOf = Integer.valueOf(imageHeightWidth.getHeight());
                        groupOfflineModel.setWidth(Integer.valueOf(imageHeightWidth.getWidth()));
                        groupOfflineModel.setHeight(valueOf);
                    } catch (Exception e4) {
                        Timber.e(e4);
                    }
                }
            }
            this.chatViewModel.addGroupModel(groupOfflineModel);
        }
    }

    private void compression(final Uri uri) {
        try {
            this.activeCompressions.incrementAndGet();
            final Context context = getContext();
            runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.showProgressDialog();
                }
            });
            final List singletonList = Collections.singletonList(uri);
            final List list = (List) singletonList.stream().map(new Function() {
                @Override
                public final Object apply(Object obj) {
                    return AgentBroadcastChatActivity.lambda$compression$11((Uri) obj);
                }
            }).collect(Collectors.toList());
            new Thread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m928x125aa0e5(context, singletonList, list, uri);
                }
            }).start();
        } catch (Exception unused) {
            Toast.makeText((Context) this, (CharSequence) "Something went wrong try again later.", 1).show();
        }
    }

    static String lambda$compression$11(Uri uri) {
        if (uri.getLastPathSegment() != null) {
            return uri.getLastPathSegment();
        }
        return "video_" + System.currentTimeMillis() + ".mp4";
    }

    void m928x125aa0e5(Context context, List list, List list2, Uri uri) {
        VideoCompressor.start(context, list, false, null, new AppSpecificStorageConfiguration("media"), new Configuration(VideoQuality.MEDIUM, false, null, false, false, null, null, list2), new AnonymousClass8(uri, context));
    }

    class AnonymousClass8 implements CompressionListener {
        final Context val$context;
        final Uri val$uri;

        static void lambda$onSuccess$0() {
        }

        @Override
        public void onStart(int index) {
        }

        AnonymousClass8(final Uri val$uri, final Context val$context) {
            this.val$uri = val$uri;
            this.val$context = val$context;
        }

        @Override
        public void onSuccess(int index, long size, final String path) {
            AgentBroadcastChatActivity agentBroadcastChatActivity = AgentBroadcastChatActivity.this;
            final Uri uri = this.val$uri;
            final Context context = this.val$context;
            agentBroadcastChatActivity.runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass8.this.m964xeccbb6f1(path, uri, context);
                }
            });
        }

        void m964xeccbb6f1(String str, Uri uri, Context context) {
            Timber.e("onSuccess: %s", new Object[]{str});
            AgentBroadcastChatActivity.this.progressMap.put(uri, Float.valueOf(100.0f));
            if (!Helper.isFileGreaterThan(new File(str), 20)) {
                AgentBroadcastChatActivity.this.submitChatResponse(str, Constants.CHAT_TYPE.VIDEO.name(), Helper.getVideoDuration(context, uri));
            } else {
                DialogHelper.showReasonDialog(context, AgentBroadcastChatActivity.this.getString(2131952988), AgentBroadcastChatActivity.this.getString(2131952253), new DialogHelper.ConfirmationListener() {
                    @Override
                    public final void onPositiveClick() {
                        AgentBroadcastChatActivity.AnonymousClass8.lambda$onSuccess$0();
                    }
                });
            }
            AgentBroadcastChatActivity.this.checkAndDismissProgressDialog();
        }

        @Override
        public void onFailure(int index, String failureMessage) {
            Timber.e("onFailure: %s", new Object[]{failureMessage});
            AgentBroadcastChatActivity agentBroadcastChatActivity = AgentBroadcastChatActivity.this;
            final Uri uri = this.val$uri;
            agentBroadcastChatActivity.runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass8.this.m962xc2bab2b9(uri);
                }
            });
        }

        void m962xc2bab2b9(Uri uri) {
            AgentBroadcastChatActivity.this.progressMap.remove(uri);
            AgentBroadcastChatActivity.this.checkAndDismissProgressDialog();
        }

        @Override
        public void onProgress(int index, float progressPercent) {
            AgentBroadcastChatActivity.this.progressMap.put(this.val$uri, Float.valueOf(progressPercent));
            long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - AgentBroadcastChatActivity.this.lastUpdateTime >= AgentBroadcastChatActivity.UPDATE_INTERVAL) {
                AgentBroadcastChatActivity.this.lastUpdateTime = currentTimeMillis;
                AgentBroadcastChatActivity.this.handler.post(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.AnonymousClass8.this.m963xe5d23015();
                    }
                });
            }
        }

        void m963xe5d23015() {
            float calculateAverageProgress = AgentBroadcastChatActivity.this.calculateAverageProgress();
            Timber.e("run: progressPercent %s", new Object[]{Float.valueOf(calculateAverageProgress)});
            AgentBroadcastChatActivity.this.progressDialogPercent(calculateAverageProgress);
        }

        @Override
        public void onCancelled(int index) {
            AgentBroadcastChatActivity agentBroadcastChatActivity = AgentBroadcastChatActivity.this;
            final Uri uri = this.val$uri;
            agentBroadcastChatActivity.runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass8.this.m961xddbe6dc2(uri);
                }
            });
        }

        void m961xddbe6dc2(Uri uri) {
            AgentBroadcastChatActivity.this.progressMap.remove(uri);
            AgentBroadcastChatActivity.this.checkAndDismissProgressDialog();
        }
    }

    public void checkAndDismissProgressDialog() {
        Timber.d("active compressions: %s", new Object[]{this.activeCompressions});
        if (this.activeCompressions.decrementAndGet() == 0) {
            hideProgressDialog();
        }
    }

    public float calculateAverageProgress() {
        Iterator<Float> it = this.progressMap.values().iterator();
        int i = 0;
        float f = 0.0f;
        while (it.hasNext()) {
            f += it.next().floatValue();
            i++;
        }
        if (i == 0) {
            return 0.0f;
        }
        return f / i;
    }

    private void onBackClick() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailToolbar.goBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public final void onClick(View view) {
                AgentBroadcastChatActivity.this.m944x4534e4a(view);
            }
        });
    }

    void m944x4534e4a(View view) {
        onBackPressed();
    }

    private void getLoginResponse() {
        LoginResponse loginResponse = (LoginResponse) new Gson().fromJson(SharedPref.getString(this, PrefKeys.LOGIN_RESPONSE), LoginResponse.class);
        this.loginResponse = loginResponse;
        this.name = loginResponse.getName();
    }

    private void toggle() {
        if (this.menuKeyboard.isShowing()) {
            this.menuKeyboard.dismiss();
        } else {
            this.menuKeyboard.show();
        }
    }

    private void setProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        this.progressDialog = progressDialog;
        progressDialog.setTitle(getString(2131953045));
        this.progressDialog.setCancelable(false);
    }

    private void showProgressDialog(boolean isVisible) {
        if (isVisible) {
            ProgressDialog progressDialog = this.progressDialog;
            if (progressDialog != null) {
                progressDialog.show();
                return;
            }
            return;
        }
        ProgressDialog progressDialog2 = this.progressDialog;
        if (progressDialog2 != null) {
            progressDialog2.dismiss();
        }
    }

    private void showDownloadProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        this.progressDialog = progressDialog;
        progressDialog.setTitle(getString(2131951964));
        this.progressDialog.setProgressStyle(1);
        this.progressDialog.setCancelable(false);
        this.progressDialog.setIndeterminate(false);
        this.progressDialog.setMax(100);
        this.progressDialog.setProgress(0);
        if (this.progressDialog.isShowing()) {
            return;
        }
        this.progressDialog.show();
    }

    public void showProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        this.progressDialog = progressDialog;
        progressDialog.setTitle(getString(2131951907));
        this.progressDialog.setProgressStyle(1);
        this.progressDialog.setCancelable(false);
        this.progressDialog.setIndeterminate(false);
        this.progressDialog.setMax(100);
        this.progressDialog.setProgress(0);
        this.progressDialog.show();
    }

    public void progressDialogPercent(float progress) {
        ProgressDialog progressDialog = this.progressDialog;
        if (progressDialog == null || !progressDialog.isShowing()) {
            return;
        }
        this.progressDialog.setProgress((int) progress);
    }

    private void hideProgressDialog() {
        ProgressDialog progressDialog = this.progressDialog;
        if (progressDialog == null || !progressDialog.isShowing()) {
            return;
        }
        this.progressDialog.dismiss();
        setProgressDialog();
    }

    private void openGallery() {
        ImagePicker.Companion.with(this).galleryOnly().crop().allowMultiple().galleryMimeTypes(new String[]{"video/*", "image/*"}).start(new Function2() {
            public final Object invoke(Object obj, Object obj2) {
                return AgentBroadcastChatActivity.this.m952xac5df965((Integer) obj, (Intent) obj2);
            }
        });
    }

    Unit m952xac5df965(Integer num, Intent intent) {
        if (num.intValue() == -1) {
            new ArrayList();
            ArrayList<GalleryFile> parcelableArrayListExtra = intent.getParcelableArrayListExtra("extra.file_path");
            Timber.i("galleryFiles: %s", new Object[]{parcelableArrayListExtra});
            if (parcelableArrayListExtra != null && !parcelableArrayListExtra.isEmpty()) {
                for (GalleryFile galleryFile : parcelableArrayListExtra) {
                    Timber.i("GalleryFile: %s", new Object[]{galleryFile.getPath()});
                    Timber.i("GalleryFile: %s", new Object[]{galleryFile.getType()});
                    if (galleryFile.getType().equals(GalleryProvider.FILETYPE.IMAGE)) {
                        Intent intent2 = new Intent();
                        intent2.setData(Uri.fromFile(new File(galleryFile.getPath())));
                        intent2.putExtra("uri", Uri.fromFile(new File(galleryFile.getPath())));
                        imageData(intent2);
                    } else {
                        try {
                            canCompress(Uri.parse(galleryFile.getPath()));
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "Error " + e, 0).show();
                        }
                    }
                }
            } else if (intent.getData() != null && intent.getData() != null) {
                imageData(intent);
            }
        }
        return Unit.INSTANCE;
    }

    private void openCamera() {
        EmojiPopup emojiPopup = this.emojiPopup;
        if (emojiPopup != null && emojiPopup.isShowing()) {
            showEmojiIcon(true);
            this.emojiPopup.dismiss();
        }
        ImagePicker.Companion.with(this).cameraOnly().crop().start(new Function2() {
            public final Object invoke(Object obj, Object obj2) {
                return AgentBroadcastChatActivity.this.m951xeca6f05((Integer) obj, (Intent) obj2);
            }
        });
    }

    Unit m951xeca6f05(Integer num, Intent intent) {
        if (num.intValue() == -1 && intent.getData() != null && intent.getData() != null) {
            imageData(intent);
        }
        return Unit.INSTANCE;
    }

    private void openDocuments() {
        Intent intent = new Intent("android.intent.action.OPEN_DOCUMENT");
        intent.addCategory("android.intent.category.OPENABLE");
        intent.setType("*/*");
        intent.putExtra("android.intent.extra.MIME_TYPES", new String[]{"audio/*", "application/*", "application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        intent.putExtra("android.intent.extra.ALLOW_MULTIPLE", true);
        startActivityForResult(intent, 5000);
    }

    private void imageData(Intent data) {
        if (data.getData() == null || data.getData() == null || data.getData() == null) {
            return;
        }
        if (Helper.isVideoFile(data.getData().toString())) {
            if (!data.hasExtra("uri") || data.getStringExtra("uri") == null) {
                return;
            }
            try {
                canCompress(Uri.parse(data.getStringExtra("uri")));
                return;
            } catch (IOException e) {
                Toast.makeText(getContext(), "Error " + e, 0).show();
                return;
            }
        }
        cameraResult(data);
    }

    private void cameraResult(Intent data) {
        try {
            final Uri data2 = data.getData();
            Timber.e("onItemPick: m %s", new Object[]{MediaStore.Images.Media.getBitmap(getContentResolver(), data2)});
            LocalDB.databaseWriteExecutor.execute(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m926xdde077d5(data2);
                }
            });
        } catch (IOException e) {
            showProgressDialog(false);
            e.printStackTrace();
        } catch (Exception unused) {
            showProgressDialog(false);
            Toast.makeText((Context) this, (CharSequence) "Something went wrong", 0).show();
        }
    }

    void m926xdde077d5(Uri uri) {
        final String compressedImageFile = CompressFile.getCompressedImageFile(uri, getContext());
        if (compressedImageFile == null) {
            runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m924xf2ec2b53();
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m925x68665194(compressedImageFile);
                }
            });
        }
    }

    void m924xf2ec2b53() {
        Toast.makeText((Context) this, (CharSequence) getString(2131952060), 0).show();
    }

    void m925x68665194(String str) {
        submitChatResponse(str, Constants.CHAT_TYPE.IMAGE.name(), 0L);
    }

    private void startReplyFlow(GroupModel chatModel, int position) {
        int i;
        if (this.replyId == null) {
            AnimatorHelper.expand(((ActivityTaskDetailBinding) this.binding).replyViewParent);
            this.viewMessageInputBinding.messageInput.requestFocus();
            Helper.showSoftKeyboard(this);
        }
        this.replyId = chatModel.getId();
        this.replyMessage = chatModel.getMessage();
        this.replyType = chatModel.getMessageType();
        boolean equals = (chatModel.getSenderId() + chatModel.getSenderType()).equals(this.accountId + this.role);
        Helper.getColor(chatModel.getSenderName(), false);
        if (!equals) {
            i = Helper.getColor(chatModel.getSenderName(), false);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.userName.setTextColor(i);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.userName.setText(chatModel.getSenderName());
        } else {
            int color = Helper.getColor(getString(2131952981), false);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.userName.setTextColor(color);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.userName.setText(getString(2131952981));
            i = color;
        }
        ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setVisibility(0);
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.TEXT.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(chatModel.getMessage());
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setVisibility(8);
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.IMAGE.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131231676);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(getString(2131952969));
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.VIDEO.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131231676);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(getString(2131952979));
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.DOCUMENT.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131231669);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(getString(2131952975));
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.LOCATION.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(getString(2131952970));
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131231636);
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.AUDIO.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131231523);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(getString(2131952959));
        } else if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.CONTACT.name())) {
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyPhoto.setImageResource(2131230886);
            ((ActivityTaskDetailBinding) this.binding).replayLayout.replyMessageText.setText(chatModel.getMessage());
        }
        ((ActivityTaskDetailBinding) this.binding).replayLayout.view4.setBackgroundColor(i);
    }

    void handleIntent(final IntentModel intentModel) {
        IntentModel.Types types = intentModel.getTypes();
        Timber.e("Type --- %s", new Object[]{types});
        if (types != null) {
            if (types.equals(IntentModel.Types.TEXT)) {
                if (intentModel.getUri() != null) {
                    this.viewMessageInputBinding.messageInput.setText(intentModel.getUri());
                    return;
                }
                return;
            }
            if (types.equals(IntentModel.Types.IMAGE)) {
                try {
                    File file = intentModel.getFile();
                    Intent intent = new Intent((Context) this, (Class<?>) EditorActivity.class);
                    intent.putExtra("imageUri", Uri.fromFile(file).toString());
                    startActivityForResult(intent, 401);
                    return;
                } catch (Exception e) {
                    Timber.e(e, "Error: ", new Object[0]);
                    Toast.makeText(getContext(), "File not found", 0).show();
                    return;
                }
            }
            if (types.equals(IntentModel.Types.PDF) || types.equals(IntentModel.Types.DOCS)) {
                new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m931x651790aa(intentModel);
                    }
                }, 200L);
            } else if (types.equals(IntentModel.Types.VIDEO)) {
                new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m934xc586036d(intentModel);
                    }
                }, 200L);
            } else if (types.equals(IntentModel.Types.AUDIO)) {
                new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m936xb07a4fef(intentModel);
                    }
                }, 200L);
            }
        }
    }

    void m931x651790aa(final IntentModel intentModel) {
        try {
            LocalDB.databaseWriteExecutor.execute(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m930x4c984714(intentModel);
                }
            });
        } catch (Exception e) {
            Timber.e(e, "Error: ", new Object[0]);
            Toast.makeText(getContext(), "File not found", 0).show();
        }
    }

    void m930x4c984714(IntentModel intentModel) {
        try {
            submitChatResponse(intentModel.getFile().getPath(), Constants.CHAT_TYPE.DOCUMENT.name(), 0L);
        } catch (Exception e) {
            Timber.e(e);
        }
    }

    void m934xc586036d(final IntentModel intentModel) {
        try {
            LocalDB.databaseWriteExecutor.execute(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m933x500bdd2c(intentModel);
                }
            });
        } catch (Exception e) {
            Timber.e(e, "Error: ", new Object[0]);
            Toast.makeText(getContext(), "File not found", 0).show();
        }
    }

    void m933x500bdd2c(IntentModel intentModel) {
        try {
            final File file = intentModel.getFile();
            runOnUiThread(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m932xda91b6eb(file);
                }
            });
        } catch (Exception e) {
            Timber.e(e);
            Toast.makeText((Context) this, (CharSequence) ("" + e.getMessage()), 0).show();
        }
    }

    void m932xda91b6eb(File file) {
        try {
            submitChatResponse(file.getPath(), Constants.CHAT_TYPE.VIDEO.name(), Helper.getDuration(file));
        } catch (Exception e) {
            Timber.e(e);
            Toast.makeText((Context) this, (CharSequence) ("" + e.getMessage()), 0).show();
        }
    }

    void m936xb07a4fef(final IntentModel intentModel) {
        try {
            LocalDB.databaseWriteExecutor.execute(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.this.m935x3b0029ae(intentModel);
                }
            });
        } catch (Exception e) {
            Timber.e(e, "Error: ", new Object[0]);
            Toast.makeText(getContext(), "File not found", 0).show();
        }
    }

    void m935x3b0029ae(IntentModel intentModel) {
        try {
            File file = intentModel.getFile();
            submitChatResponse(file.getPath(), Constants.CHAT_TYPE.AUDIO.name(), Helper.getDuration(file) * 1000);
        } catch (Exception e) {
            Timber.e(e);
        }
    }

    public void handleIntents() {
        try {
            Intent intent = getIntent();
            if (intent == null) {
                return;
            }
            String action = intent.getAction();
            String type = intent.getType();
            if ("android.intent.action.SEND".equals(action) && type != null) {
                if ("application/pdf".equals(type)) {
                    handleSend(intent, IntentModel.Types.PDF);
                } else if (type.startsWith("image/")) {
                    handleSend(intent, IntentModel.Types.IMAGE);
                } else if (type.startsWith("video/")) {
                    handleSend(intent, IntentModel.Types.VIDEO);
                } else if (type.startsWith("audio/")) {
                    handleSend(intent, IntentModel.Types.AUDIO);
                }
            }
        } catch (Exception e) {
            Timber.e(e, "Error: ", new Object[0]);
        }
    }

    void handleSend(Intent intent, IntentModel.Types type) {
        IntentModel intentModel;
        Uri uri = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM");
        if (uri != null) {
            Timber.e("image Uri %s", new Object[]{uri});
            if (type.equals(IntentModel.Types.IMAGE)) {
                intentModel = new IntentModel(IntentModel.Types.IMAGE, String.valueOf(uri));
            } else if (type.equals(IntentModel.Types.PDF)) {
                intentModel = new IntentModel(IntentModel.Types.PDF, String.valueOf(uri));
            } else if (type.equals(IntentModel.Types.VIDEO)) {
                intentModel = new IntentModel(IntentModel.Types.VIDEO, String.valueOf(uri));
            } else {
                intentModel = type.equals(IntentModel.Types.AUDIO) ? new IntentModel(IntentModel.Types.AUDIO, String.valueOf(uri)) : null;
            }
            if (intentModel != null) {
                handleIntent(intentModel);
            }
        }
    }

    protected void onDestroy() {
        this.menuKeyboard.clear();
        ProgressDialog progressDialog = this.progressDialog;
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        AlertDialog alertDialog = this.alertDialog;
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        releasePlayer();
        CompositeDisposable compositeDisposable = this.disposable;
        if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
            this.disposable.dispose();
            this.disposable.clear();
        }
        super.onDestroy();
    }

    private boolean isLastVisible() {
        CustomLinearLayoutManager layoutManager = ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager();
        return ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getAdapter() != null && (layoutManager != null ? layoutManager.findLastVisibleItemPosition() : 0) >= ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getAdapter().getItemCount() - 1;
    }

    @Override
    public PopupWindow getPopup() {
        return this.menuKeyboard;
    }

    @Override
    public void onPopUpBack() {
        super.onPopUpBack();
        EmojiPopup emojiPopup = this.emojiPopup;
        if (emojiPopup == null || !emojiPopup.isShowing()) {
            return;
        }
        showEmojiIcon(true);
    }

    @Override
    public void onImageClick(GroupModel chatModel, int position) {
        Intent intent = new Intent((Context) this, (Class<?>) ImageShowActivity.class);
        intent.putExtra("pics", chatModel.getMessage());
        startActivity(intent);
    }

    @Override
    public void onVideoClick(GroupModel chatModel, int position) {
        if (!chatModel.getMessage().contains("https://")) {
            Helper.openPlayer(getContext(), chatModel.getMessage());
        } else if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
            Helper.openPlayer(getContext(), this.chatViewModel.getFilePath(getContext(), chatModel, false));
        } else {
            this.chatViewModel.createDownload(getContext(), chatModel, false, false, false);
        }
    }

    void m949x95ec02c1(GroupModel groupModel, DialogInterface dialogInterface, int i) {
        deleteMessageResponse(groupModel);
    }

    @Override
    public void onLongClick(final GroupModel chatModel, int position) {
        new AlertDialog.Builder(this).setMessage(getString(2131952995) + "?").setPositiveButton(getString(2131953093), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                AgentBroadcastChatActivity.this.m949x95ec02c1(chatModel, dialogInterface, i);
            }
        }).setNegativeButton(getString(2131952360), new DialogInterface.OnClickListener() {
            @Override
            public final void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();
    }

    @Override
    public void onAudioClick(GroupModel chatModel) {
        super.onAudioClick(chatModel);
        if (!chatModel.getMessage().contains("https://")) {
            MessageAdapter messageAdapter = this.messageAdapter;
            if (messageAdapter != null) {
                messageAdapter.playAudio(chatModel.getMessage());
                return;
            }
            return;
        }
        if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
            String filePath = this.chatViewModel.getFilePath(getContext(), chatModel, false);
            MessageAdapter messageAdapter2 = this.messageAdapter;
            if (messageAdapter2 != null) {
                messageAdapter2.playAudio(filePath);
                return;
            }
            return;
        }
        this.chatViewModel.createDownload(getContext(), chatModel, false, false, false);
    }

    @Override
    public void onDocumentClick(GroupModel chatModel, int position) {
        onDocumentClick(chatModel);
    }

    private void onDocumentClick(GroupModel chatModel) {
        try {
            if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
                try {
                    Uri uriForFile = FileProvider.getUriForFile(getApplicationContext(), "app.ri1l0.provider", new File(this.chatViewModel.getFilePath(getContext(), chatModel, false)));
                    Intent intent = new Intent();
                    intent.addFlags(268435456);
                    intent.setAction("android.intent.action.VIEW");
                    intent.addFlags(1);
                    intent.setDataAndType(uriForFile, Files.getMimeFromUrl(chatModel.getMessage()));
                    startActivity(intent);
                } catch (ActivityNotFoundException unused) {
                    Toast.makeText((Context) this, 2131952361, 0).show();
                }
            } else {
                this.chatViewModel.createDownload(getContext(), chatModel, false, false, false);
            }
        } catch (Exception e) {
            Toast.makeText((Context) this, (CharSequence) ("" + e.getMessage()), 0).show();
        }
    }

    @Override
    public void onReplyClick(GroupModel chatModel, int position) {
        startReplyFlow(chatModel, position);
    }

    @Override
    public void onReplyMessage(GroupModel chatModel, int position) {
        boolean z;
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter == null) {
            return;
        }
        if (messageAdapter.getSelectedItemCount() > 0) {
            enableActionMode(position);
            return;
        }
        Iterator<GroupModel> it = this.messageAdapter.getUserMessagesList().iterator();
        int i = 0;
        while (true) {
            if (!it.hasNext()) {
                z = false;
                break;
            } else {
                if (it.next().getId().equals(chatModel.getReplyMessageId())) {
                    z = true;
                    break;
                }
                i++;
            }
        }
        if (!z) {
            reset();
            this.chatViewModel.fromSearch = true;
            this.searchMessageId = chatModel.getReplyMessageId();
            this.chatViewModel.messageId = chatModel.getReplyMessageId();
            Timber.e("current reply id %s", new Object[]{this.currentPage});
            getChatResponse(true, false);
            return;
        }
        Timber.e("scroll position %s", new Object[]{Integer.valueOf(i)});
        if (((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager() != null) {
            ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager().smoothScrollToPosition(((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView, new RecyclerView.State(), i);
        }
        this.messageAdapter.highLightBackground(i, true);
    }

    @Override
    public void onShareClick(GroupModel chatModel, int position) {
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.TEXT.name())) {
            Helper.shareText(chatModel.getMessage(), getContext());
            return;
        }
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.LOCATION.name())) {
            return;
        }
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.DOCUMENT.name())) {
            this.chatViewModel.createDownload(getContext(), chatModel, true, true, false);
        } else if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
            shareFile(chatModel);
        } else {
            this.chatViewModel.createDownload(getContext(), chatModel, false, true, false);
        }
    }

    @Override
    public void onCopyClick(GroupModel chatModel, int position) {
        Helper.copyToClipboard(getContext(), chatModel.getMessage());
    }

    @Override
    public void setActionMode(int position) {
        enableActionMode(position);
    }

    @Override
    public void onForward(GroupModel groupModel, int position) {
        if (this.messageAdapter != null) {
            enableActionMode(position);
        }
    }

    @Override
    public void onRetryClick(GroupModel chatModel, int position) {
        if (Helper.isConnected(getContext())) {
            this.chatViewModel.syncChat(chatModel);
        } else {
            Toast.makeText((Context) this, (CharSequence) getString(2131952366), 0).show();
        }
    }

    private void shareFile(GroupModel chatModel) {
        File file = new File(this.chatViewModel.getFilePath(getContext(), chatModel, false));
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.IMAGE.name())) {
            Uri uriForFile = FileProvider.getUriForFile(getApplicationContext(), "app.ri1l0.provider", file);
            Intent addFlags = ShareCompat.IntentBuilder.from(this).setStream(uriForFile).setType("image/*").setChooserTitle("Share image...").getIntent().setDataAndType(uriForFile, "image/*").addFlags(1);
            Iterator<ResolveInfo> it = getPackageManager().queryIntentActivities(addFlags, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST).iterator();
            while (it.hasNext()) {
                grantUriPermission(it.next().activityInfo.packageName, uriForFile, 3);
            }
            startActivity(addFlags);
            return;
        }
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.VIDEO.name())) {
            Uri uriForFile2 = FileProvider.getUriForFile(getApplicationContext(), "app.ri1l0.provider", file);
            Intent addFlags2 = ShareCompat.IntentBuilder.from(this).setStream(uriForFile2).setType("video/*").setChooserTitle("Share audio...").getIntent().setDataAndType(uriForFile2, "audio/*").addFlags(1);
            Iterator<ResolveInfo> it2 = getPackageManager().queryIntentActivities(addFlags2, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST).iterator();
            while (it2.hasNext()) {
                grantUriPermission(it2.next().activityInfo.packageName, uriForFile2, 3);
            }
            startActivity(addFlags2);
            return;
        }
        if (chatModel.getMessageType().equals(Constants.CHAT_TYPE.AUDIO.name())) {
            Uri uriForFile3 = FileProvider.getUriForFile(getApplicationContext(), "app.ri1l0.provider", file);
            Intent addFlags3 = ShareCompat.IntentBuilder.from(this).setStream(uriForFile3).setType("audio/*").setChooserTitle("Share audio...").getIntent().setDataAndType(uriForFile3, "audio/*").addFlags(1);
            Iterator<ResolveInfo> it3 = getPackageManager().queryIntentActivities(addFlags3, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST).iterator();
            while (it3.hasNext()) {
                grantUriPermission(it3.next().activityInfo.packageName, uriForFile3, 3);
            }
            startActivity(addFlags3);
            return;
        }
        Uri uriForFile4 = FileProvider.getUriForFile(getApplicationContext(), "app.ri1l0.provider", new File(this.chatViewModel.getFilePath(getContext(), chatModel, true)));
        Intent addFlags4 = ShareCompat.IntentBuilder.from(this).setStream(uriForFile4).setType("application/pdf").setChooserTitle("Share pdf...").getIntent().setDataAndType(uriForFile4, "application/pdf").addFlags(1);
        Iterator<ResolveInfo> it4 = getPackageManager().queryIntentActivities(addFlags4, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST).iterator();
        while (it4.hasNext()) {
            grantUriPermission(it4.next().activityInfo.packageName, uriForFile4, 3);
        }
        startActivity(addFlags4);
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            @Override
            public final void run() {
                AgentBroadcastChatActivity.this.handleIntents();
            }
        }, 1000L);
        if (!intent.hasExtra("notification_clicked") || !intent.getBooleanExtra("notification_clicked", false)) {
            Timber.e("onNewIntent: not this %s", new Object[]{Boolean.valueOf(intent.hasExtra("notification_clicked"))});
            return;
        }
        long j = SharedPref.getLong(getContext(), PrefKeys.NOTIFICATION_CHAT_ID, -1L);
        Timber.e("onNewIntent:  int %s", new Object[]{Long.valueOf(j)});
        Timber.e("onNewIntent: act %s", new Object[]{Long.valueOf(chatId)});
        if (j == -1) {
            onBackPressed();
        }
        if (chatId == j) {
            setToolbar();
            reset();
            getChatResponse(true, false);
        } else {
            chatId = j;
            finish();
            startActivity(intent);
        }
        clearNotificationCount();
        App.notificationAvailable = false;
    }

    @Override
    public void menuOnClick(final GridMenuAdapter.Menu menu) {
        SoftKeyBoardPopup softKeyBoardPopup = this.menuKeyboard;
        if (softKeyBoardPopup != null) {
            softKeyBoardPopup.dismiss();
        }
        new Handler(Looper.myLooper()).postDelayed(new Runnable() {
            @Override
            public final void run() {
                AgentBroadcastChatActivity.this.m941x732419a6(menu);
            }
        }, 300L);
    }

    void m941x732419a6(GridMenuAdapter.Menu menu) {
        if (menu.getName().equals(getString(2131952965))) {
            openDocuments();
            return;
        }
        if (menu.getName().equals(getString(2131952989))) {
            openCamera();
            return;
        }
        if (menu.getName().equals(getString(2131952979))) {
            startActivityForResult(new Intent("android.media.action.VIDEO_CAPTURE"), 1000);
            return;
        }
        if (menu.getName().equals(getString(2131952967))) {
            openGallery();
        } else if (menu.getName().equals(getString(2131952186))) {
            showPlacePicker();
        } else {
            menu.getName().equals(getString(2131951910));
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {
            if (resultCode == -1 && data != null) {
                try {
                    canCompress(data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if ((requestCode != 5000 || resultCode != -1) && ((requestCode != 500 || resultCode != -1) && requestCode == 401 && resultCode == -1 && data != null)) {
            submitChatResponse(new File(data.getStringExtra("imagePath")).getPath(), Constants.CHAT_TYPE.IMAGE.name(), 0L);
        }
        if (requestCode == 301 && resultCode == -1) {
            reset();
            getChatResponse(true, false);
        }
        if (requestCode == 301 && resultCode == 1005) {
            reset();
            getChatResponse(true, false);
            setToolbar();
        }
        if (requestCode == 301 && resultCode == 1006) {
            onBackPressed();
        }
        if (requestCode == 301 && resultCode == 1007 && data != null) {
            this.adminOnly = data.getBooleanExtra("adminOnly", false);
            getIntent().putExtra("adminOnly", this.adminOnly);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != 200 || grantResults.length == 0) {
            return;
        }
        if (Build.VERSION.SDK_INT >= 30) {
            this.permissionToRecordAccepted = grantResults[0] == 0 && grantResults[1] == 0 && grantResults[2] == 0;
        } else {
            this.permissionToRecordAccepted = grantResults[0] == 0 && grantResults[1] == 0 && grantResults[2] == 0;
        }
    }

    class AnonymousClass9 extends BroadcastReceiver {
        AnonymousClass9() {
        }

        @Override
        public void onReceive(final Context context, Intent intent) {
            if (intent.getAction().equals(Constants.NOTIFICATION_REFRESH)) {
                intent.setAction("");
                Timber.e("NOTIFICATION_REFRESH %s", new Object[]{Boolean.valueOf(AgentBroadcastChatActivity.this.isCurrentSender)});
                AgentBroadcastChatActivity.this.isCurrentSender = false;
                intent.getLongExtra("chat_id", 0L);
                String stringExtra = intent.getStringExtra("chat_message");
                final GroupModel groupModel = null;
                if (stringExtra != null && !stringExtra.isEmpty()) {
                    groupModel = (GroupModel) new Gson().fromJson(stringExtra, GroupModel.class);
                    groupModel.setCreatedAt(DateHelper.formatDateByPattern(groupModel.getCreatedAt(), "MMM dd, yyyy, hh:mm:ss a", "yyyy-MM-dd HH:mm:ss", "Asia/Kolkata"));
                    groupModel.setCreationDate(DateHelper.formatDateByPattern(groupModel.getCreatedAt(), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"));
                }
                App.notificationAvailable = false;
                AgentBroadcastChatActivity.this.clearNotificationCount();
                new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.AnonymousClass9.this.m966xf4e271d2(groupModel, context);
                    }
                }, 100L);
            }
        }

        void m966xf4e271d2(GroupModel groupModel, Context context) {
            if (groupModel != null) {
                if (groupModel.getSenderType().equals(AgentBroadcastChatActivity.this.role) && String.valueOf(groupModel.getSenderId()).equals(AgentBroadcastChatActivity.this.accountId)) {
                    return;
                }
                if (!Helper.isAwake(AgentBroadcastChatActivity.this.getContext())) {
                    AgentBroadcastChatActivity.this.playSound(context);
                }
                if (AgentBroadcastChatActivity.this.messageAdapter != null) {
                    if (AgentBroadcastChatActivity.this.isVisible) {
                        Helper.playSound(AgentBroadcastChatActivity.this.getContext(), 2131886132);
                    }
                    if (AgentBroadcastChatActivity.this.chatViewModel == null || !AgentBroadcastChatActivity.this.chatViewModel.fromSearch) {
                        AgentBroadcastChatActivity.this.messageAdapter.addItem(groupModel, true);
                        AgentBroadcastChatActivity.this.scrollRv();
                        AgentBroadcastChatActivity.this.notifyCall();
                        return;
                    } else {
                        AgentBroadcastChatActivity.this.chatViewModel.fromSearch = false;
                        AgentBroadcastChatActivity.this.chatViewModel.messageId = -1L;
                        AgentBroadcastChatActivity.this.searchMessageId = -1L;
                        AgentBroadcastChatActivity.this.reset();
                        AgentBroadcastChatActivity.this.getChatResponse(true, false);
                        return;
                    }
                }
                return;
            }
            Timber.e("reset ", new Object[0]);
            AgentBroadcastChatActivity.this.reset();
            new Handler(Looper.myLooper()).postDelayed(new Runnable() {
                @Override
                public final void run() {
                    AgentBroadcastChatActivity.AnonymousClass9.this.m965xf558d7d1();
                }
            }, 300L);
        }

        void m965xf558d7d1() {
            AgentBroadcastChatActivity.this.getChatResponse(true, false);
        }
    }

    private void registerReceiver() {
        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.NOTIFICATION_REFRESH);
        localBroadcastManager.registerReceiver(this.broadcastReceiver, intentFilter);
    }

    private void unRegisterReceiver() {
        if (this.broadcastReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(this.broadcastReceiver);
        }
    }

    public void onBackPressed() {
        if (isTaskRoot()) {
            Intent intent = new Intent((Context) this, (Class<?>) HomeActivity.class);
            if (this.isAgent) {
                intent = new Intent((Context) this, (Class<?>) AgentHomeActivity.class);
            }
            intent.addFlags(268468224);
            finish();
            startActivity(intent);
        } else {
            GroupViewModel groupViewModel = this.chatViewModel;
            if (groupViewModel != null && groupViewModel.forward) {
                Intent intent2 = new Intent((Context) this, (Class<?>) HomeActivity.class);
                if (this.isAgent) {
                    intent2 = new Intent((Context) this, (Class<?>) AgentHomeActivity.class);
                }
                intent2.addFlags(268468224);
                finish();
                startActivity(intent2);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        }
        super.onBackPressed();
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver();
    }

    protected void onPause() {
        this.isVisible = false;
        releasePlayer();
        super.onPause();
    }

    protected void onStop() {
        if (!Helper.isAwake(getContext())) {
            App.isChatScreen = true;
        } else {
            unRegisterReceiver();
        }
        super.onStop();
    }

    protected void onResume() {
        this.isVisible = true;
        super.onResume();
        if (App.notificationAvailable) {
            reset();
            getChatResponse(true, false);
            handleNotification();
            App.notificationAvailable = false;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong("chatId", chatId);
        outState.putString("taskTitle", App.chatTitle);
        outState.putString(FacebookRequestErrorClassification.KEY_NAME, this.name);
        outState.putString("userId", this.accountId);
        outState.putBoolean("isCurrentSender", this.isCurrentSender);
        outState.putBoolean("adminOnly", this.adminOnly);
    }

    @Override
    public void onAudioReady(String audioUri) {
        if (audioUri == null || audioUri.isEmpty()) {
            return;
        }
        submitChatResponse(audioUri, Constants.CHAT_TYPE.AUDIO.name(), 0L);
    }

    private void releasePlayer() {
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter != null) {
            try {
                messageAdapter.stopPlayer();
            } catch (Exception e) {
                Timber.e(e, "releasePlayer: ", new Object[0]);
            }
        }
    }

    public void playSound(Context context) {
        if (SharedPref.getBoolean(getApplicationContext(), "mute")) {
            return;
        }
        MediaPlayer.create(context, 2131886113).start();
    }

    private void scrollAndHighlightBackground(long messageId) {
        boolean z;
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter == null) {
            return;
        }
        Iterator<GroupModel> it = messageAdapter.getUserMessagesList().iterator();
        int i = 0;
        while (true) {
            if (!it.hasNext()) {
                z = false;
                break;
            } else {
                if (it.next().getId().equals(Long.valueOf(messageId))) {
                    z = true;
                    break;
                }
                i++;
            }
        }
        if (z) {
            Timber.e("scroll position %s", new Object[]{Integer.valueOf(i)});
            if (((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager() != null) {
                CenterSmoothScroller centerSmoothScroller = new CenterSmoothScroller(((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getContext());
                centerSmoothScroller.setTargetPosition(i);
                ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager().startSmoothScroll(centerSmoothScroller);
                ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.getLayoutManager().scrollToPosition(i);
            }
            this.messageAdapter.highLightBackground(i, true);
        }
    }

    public void scrollRv() {
        ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.postDelayed(new Runnable() {
            @Override
            public final void run() {
                AgentBroadcastChatActivity.this.m953lambda$scrollRv$29$appcallpeuichatAgentBroadcastChatActivity();
            }
        }, 100L);
    }

    void m953lambda$scrollRv$29$appcallpeuichatAgentBroadcastChatActivity() {
        try {
            if (this.messageAdapter != null) {
                ((ActivityTaskDetailBinding) this.binding).taskDetailRecyclerView.scrollToPosition(this.messageAdapter.getItemCount() - 1);
            }
        } catch (Exception unused) {
        }
    }

    public void reset() {
        this.currentPage = -1L;
        this.bottomPage = -1L;
        this.idMapper.clear();
        this.chatModelArrayList.clear();
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter != null) {
            messageAdapter.clear();
        }
    }

    private void playVideo(GroupModel chatModel) {
        if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
            Helper.openPlayer(getContext(), this.chatViewModel.getFilePath(getContext(), chatModel, false));
        }
    }

    private void playAudio(GroupModel chatModel) {
        if (this.chatViewModel.isFileExists(getContext(), chatModel, false)) {
            String filePath = this.chatViewModel.getFilePath(getContext(), chatModel, false);
            MessageAdapter messageAdapter = this.messageAdapter;
            if (messageAdapter != null) {
                messageAdapter.playAudio(filePath);
            }
        }
    }

    private void canCompress(Uri uri) throws IOException {
        String pathFromURI = Files.getPathFromURI(getContext(), uri);
        if (pathFromURI != null) {
            if (!Helper.isFileLessThan(new File(pathFromURI), 20)) {
                compression(uri);
                return;
            } else {
                submitChatResponse(pathFromURI, Constants.CHAT_TYPE.VIDEO.name(), Helper.getVideoDuration(this, uri));
                return;
            }
        }
        compression(uri);
    }

    public void stopRecording(boolean deleteFile) {
        this.audioRecorder.stop();
        File file = this.recordFile;
        if (file == null || !deleteFile) {
            return;
        }
        file.delete();
    }

    public void clearNotificationCount() {
        LocalDB.databaseWriteExecutor.execute(new Runnable() {
            @Override
            public final void run() {
                AgentBroadcastChatActivity.this.m927x4043fdf6();
            }
        });
    }

    void m927x4043fdf6() {
        try {
            this.chatDao.dropAgentBroadcastNotification();
            handleNotification();
        } catch (Exception unused) {
        }
    }

    private void observerMessageText() {
        this.viewMessageInputBinding.recordMessageBtn.setImageResource(2131231720);
        this.viewMessageInputBinding.messageInput.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) {
                if (AgentBroadcastChatActivity.this.viewMessageInputBinding.messageInput.getText() != null) {
                    if (!AgentBroadcastChatActivity.this.viewMessageInputBinding.messageInput.getText().toString().trim().isEmpty()) {
                        AgentBroadcastChatActivity.this.recordButton.setListenForRecord(false);
                        AgentBroadcastChatActivity.this.viewMessageInputBinding.recordMessageBtn.setImageResource(2131231720);
                    } else {
                        AgentBroadcastChatActivity.this.recordButton.setListenForRecord(true);
                        AgentBroadcastChatActivity.this.viewMessageInputBinding.recordMessageBtn.setImageResource(2131232060);
                    }
                }
            }
        });
    }

    void observeSyncResponse() {
        CompositeDisposable compositeDisposable = new CompositeDisposable();
        this.disposable = compositeDisposable;
        compositeDisposable.add(SyncRxBus.getInstance().toObservable().subscribe(new Consumer() {
            public final void accept(Object obj) {
                AgentBroadcastChatActivity.this.handleSyncResponse((SyncResponse) obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                Timber.e((Throwable) obj, "error handling sync response", new Object[0]);
            }
        }));
        this.disposable.add(this.rxBus.toObservable().subscribe(new Consumer() {
            public final void accept(Object obj) {
                AgentBroadcastChatActivity.this.m942xbbb87411(obj);
            }
        }, new Consumer() {
            public final void accept(Object obj) {
                AgentBroadcastChatActivity.this.m943x31329a52((Throwable) obj);
            }
        }));
    }

    void m942xbbb87411(Object obj) throws Exception {
        if (obj instanceof Progress) {
            Progress progress = (Progress) obj;
            progressDialogPercent((progress.currentBytes * 100.0f) / progress.totalBytes);
            return;
        }
        if (obj instanceof DownloadStatus) {
            DownloadStatus downloadStatus = (DownloadStatus) obj;
            if (downloadStatus.getState().equals(DownloadStatus.STATE.ENQUEUED)) {
                showDownloadProgressDialog();
                return;
            }
            if (downloadStatus.getState().equals(DownloadStatus.STATE.FINISHED)) {
                hideProgressDialog();
                GroupModel groupModel = downloadStatus.getGroupModel();
                if (groupModel != null) {
                    if (downloadStatus.isShare()) {
                        shareFile(groupModel);
                        return;
                    }
                    if (groupModel.getMessageType().equals(Constants.CHAT_TYPE.DOCUMENT.name())) {
                        onDocumentClick(groupModel);
                        Toast.makeText(getContext(), "" + getString(2131951960), 0).show();
                        return;
                    }
                    if (groupModel.getMessageType().equals(Constants.CHAT_TYPE.AUDIO.name())) {
                        playAudio(groupModel);
                        return;
                    }
                    playVideo(groupModel);
                    Toast.makeText(getContext(), "" + getString(2131951960), 0).show();
                    return;
                }
                return;
            }
            if (downloadStatus.getState().equals(DownloadStatus.STATE.FAILED)) {
                hideProgressDialog();
                Toast.makeText(getContext(), "" + getString(2131952996), 0).show();
                return;
            }
            if (downloadStatus.getState().equals(DownloadStatus.STATE.ERROR)) {
                hideProgressDialog();
                Toast.makeText(getContext(), "" + downloadStatus.getError().getServerErrorMessage(), 0).show();
                return;
            }
            return;
        }
        if (obj instanceof Error) {
            Toast.makeText(getContext(), "" + ((Error) obj).getServerErrorMessage(), 0).show();
        }
    }

    void m943x31329a52(Throwable th) throws Exception {
        Timber.e("error handling sync response %s", new Object[]{th.getMessage()});
        Toast.makeText((Context) this, (CharSequence) ("" + th.getMessage()), 0).show();
    }

    private void handleNotification() {
        try {
            Helper.cancelNotification(this, Math.toIntExact(chatId));
            Helper.cancelNotification(this, Math.toIntExact(FirebaseNotificationService.agentBroadcastNotificationChatId));
        } catch (Exception unused) {
        }
    }

    public void handleSyncResponse(final SyncResponse response) {
        if (response.responseType == SyncRxBus.ResponseType.GROUP) {
            if (response.eventType == SyncResponseEventType.PROGRESS) {
                if (response.groupOfflineModel.getMessageType().equals(Constants.CHAT_TYPE.VIDEO.name())) {
                    return;
                }
                response.groupOfflineModel.getMessageType().equals(Constants.CHAT_TYPE.IMAGE.name());
                return;
            }
            if (response.eventType == SyncResponseEventType.SUCCESS) {
                if (this.replyId != null) {
                    this.replyId = null;
                    this.replyMessage = null;
                    this.replyType = null;
                    AnimatorHelper.collapse(((ActivityTaskDetailBinding) this.binding).replyViewParent);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m937xcf3785ed(response);
                    }
                });
                notifyCall();
                return;
            }
            if (response.eventType == SyncResponseEventType.MESSAGE_ADDED) {
                if (this.replyId != null) {
                    this.replyId = null;
                    this.replyMessage = null;
                    this.replyType = null;
                }
                if (((ActivityTaskDetailBinding) this.binding).replyViewParent.getVisibility() == 0) {
                    ((ActivityTaskDetailBinding) this.binding).replyViewParent.setVisibility(8);
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m938x44b1ac2e(response);
                    }
                });
                return;
            }
            if (response.eventType == SyncResponseEventType.FAILED_MESSAGE_DELETED) {
                reset();
                getChatResponse(true, false);
            } else if (response.eventType == SyncResponseEventType.FAILED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m939xba2bd26f(response);
                    }
                });
            } else if (response.eventType == SyncResponseEventType.MESSAGE_SYNC) {
                runOnUiThread(new Runnable() {
                    @Override
                    public final void run() {
                        AgentBroadcastChatActivity.this.m940x2fa5f8b0(response);
                    }
                });
            }
        }
    }

    void m937xcf3785ed(SyncResponse syncResponse) {
        GroupViewModel groupViewModel;
        Helper.playSound(getContext(), 2131886129);
        if (this.messageAdapter == null || syncResponse.groupModel == null || this.messageAdapter.updateItem(syncResponse.groupModel) || (groupViewModel = this.chatViewModel) == null) {
            return;
        }
        groupViewModel.groupMessage = syncResponse.groupModel;
    }

    void m938x44b1ac2e(SyncResponse syncResponse) {
        if (this.messageAdapter != null) {
            GroupViewModel groupViewModel = this.chatViewModel;
            if (groupViewModel != null && groupViewModel.fromSearch) {
                this.chatViewModel.fromSearch = false;
                this.chatViewModel.messageId = -1L;
                this.searchMessageId = -1L;
                reset();
                getChatResponse(true, false);
                return;
            }
            Timber.e("Message Added UUID --- %s", new Object[]{syncResponse.groupOfflineModel.getUuid()});
            this.messageAdapter.addItem(GroupUtils.mapToGroupModel(syncResponse.groupOfflineModel));
            scrollRv();
        }
    }

    void m939xba2bd26f(SyncResponse syncResponse) {
        if (this.messageAdapter == null || syncResponse.groupOfflineModel == null) {
            return;
        }
        this.messageAdapter.updateItem(GroupUtils.mapToGroupModel(syncResponse.groupOfflineModel));
    }

    void m940x2fa5f8b0(SyncResponse syncResponse) {
        if (this.messageAdapter == null || syncResponse.groupOfflineModel == null) {
            return;
        }
        this.messageAdapter.updateItem(GroupUtils.mapToGroupModel(syncResponse.groupOfflineModel));
    }

    @Override
    public ActivityTaskDetailBinding inflateLayout(LayoutInflater layoutInflater) {
        return ActivityTaskDetailBinding.inflate(getLayoutInflater());
    }

    private void showEmojiIcon(boolean showEmoji) {
        if (showEmoji) {
            Glide.with(getContext()).load(2131231587).into(this.viewMessageInputBinding.emoji);
        } else {
            Glide.with(getContext()).load(2131231625).into(this.viewMessageInputBinding.emoji);
        }
    }

    private void enableActionMode(int position) {
        if (this.actionMode == null) {
            this.actionMode = startSupportActionMode(this.actionModeCallback);
        }
        toggleSelection(position);
    }

    private void toggleSelection(int position) {
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter == null) {
            return;
        }
        messageAdapter.toggleSelection(position);
        int selectedItemCount = this.messageAdapter.getSelectedItemCount();
        if (selectedItemCount == 0) {
            ActionMode actionMode = this.actionMode;
            if (actionMode != null) {
                actionMode.finish();
                return;
            }
            return;
        }
        this.actionMode.setTitle(String.valueOf(selectedItemCount));
        this.actionMode.invalidate();
    }

    private class ActionModeCallback implements ActionMode.Callback {
        private ActionModeCallback() {
        }

        ActionModeCallback(AgentBroadcastChatActivity agentBroadcastChatActivity, AnonymousClass1 anonymousClass1) {
            this();
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(2131689472, menu);
            return true;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            MenuItem findItem = menu.findItem(2131364350);
            MenuItem findItem2 = menu.findItem(2131362638);
            MenuItem findItem3 = menu.findItem(2131363276);
            MenuItem findItem4 = menu.findItem(2131364587);
            MenuItem findItem5 = menu.findItem(2131362539);
            boolean z = true;
            if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() > 1) {
                findItem.setVisible(false);
                findItem2.setVisible(false);
                findItem3.setVisible(false);
                findItem4.setVisible(false);
                findItem5.setVisible(false);
            } else {
                findItem.setVisible(true);
                if (AgentBroadcastChatActivity.this.messageAdapter != null) {
                    if (AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                        GroupModel groupModel = AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().get(0);
                        if ((groupModel.getSenderId() + groupModel.getSenderType()).equals(AgentBroadcastChatActivity.this.accountId + "")) {
                            findItem3.setVisible(true);
                            findItem2.setVisible(true);
                        } else {
                            findItem2.setVisible(false);
                            findItem3.setVisible(false);
                        }
                        findItem3.setVisible(false);
                        findItem.setVisible(false);
                        String messageType = AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().get(0).getMessageType();
                        if (!messageType.equals(Constants.CHAT_TYPE.AUDIO.name()) && !messageType.equals(Constants.CHAT_TYPE.IMAGE.name()) && !messageType.equals(Constants.CHAT_TYPE.VIDEO.name()) && !messageType.equals(Constants.CHAT_TYPE.DOCUMENT.name()) && !messageType.equals(Constants.CHAT_TYPE.TEXT.name()) && !messageType.equals(Constants.CHAT_TYPE.LOCATION.name())) {
                            z = false;
                        }
                        findItem4.setVisible(z);
                        findItem5.setVisible(messageType.equals(Constants.CHAT_TYPE.TEXT.name()));
                    } else {
                        findItem4.setVisible(false);
                    }
                }
            }
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            int itemId = item.getItemId();
            if (itemId == 2131361941) {
                AgentBroadcastChatActivity.this.forwardMessage();
                return true;
            }
            if (itemId == 2131364350) {
                if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                    AgentBroadcastChatActivity agentBroadcastChatActivity = AgentBroadcastChatActivity.this;
                    agentBroadcastChatActivity.onReplyClick(agentBroadcastChatActivity.messageAdapter.getSelectedItems().get(0), 0);
                    mode.finish();
                    onDestroyActionMode(mode);
                }
                return true;
            }
            if (itemId == 2131362638) {
                if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                    AgentBroadcastChatActivity agentBroadcastChatActivity2 = AgentBroadcastChatActivity.this;
                    agentBroadcastChatActivity2.onLongClick(agentBroadcastChatActivity2.messageAdapter.getSelectedItems().get(0), 0);
                }
                return true;
            }
            if (itemId == 2131363276) {
                if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                    AgentBroadcastChatActivity agentBroadcastChatActivity3 = AgentBroadcastChatActivity.this;
                    agentBroadcastChatActivity3.onInfoClick(agentBroadcastChatActivity3.messageAdapter.getSelectedItems().get(0), 0);
                    mode.finish();
                    onDestroyActionMode(mode);
                }
                return true;
            }
            if (itemId == 2131364587) {
                if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                    AgentBroadcastChatActivity agentBroadcastChatActivity4 = AgentBroadcastChatActivity.this;
                    agentBroadcastChatActivity4.onShareClick(agentBroadcastChatActivity4.messageAdapter.getSelectedItems().get(0), 0);
                    mode.finish();
                    onDestroyActionMode(mode);
                }
                return true;
            }
            if (itemId == 2131361936) {
                AgentBroadcastChatActivity.this.messageAdapter.clearSelections();
                if (AgentBroadcastChatActivity.this.actionMode != null) {
                    AgentBroadcastChatActivity.this.actionMode.finish();
                }
                return true;
            }
            if (itemId != 2131362539) {
                return false;
            }
            if (AgentBroadcastChatActivity.this.messageAdapter != null && AgentBroadcastChatActivity.this.messageAdapter.getSelectedItems().size() == 1) {
                ?? r5 = AgentBroadcastChatActivity.this;
                Helper.copyToClipboard(r5, ((AgentBroadcastChatActivity) r5).messageAdapter.getSelectedItems().get(0).getMessage());
                mode.finish();
                onDestroyActionMode(mode);
            }
            return true;
        }

        public void onDestroyActionMode(ActionMode mode) {
            AgentBroadcastChatActivity.this.messageAdapter.clearSelections();
            AgentBroadcastChatActivity.this.actionMode = null;
        }
    }

    public void forwardMessage() {
        ArrayList<GroupModel> selectedItems;
        if (this.messageAdapter.getSelectedItemCount() == 0) {
            Toast.makeText((Context) this, (CharSequence) getString(2131953004), 0).show();
            return;
        }
        MessageAdapter messageAdapter = this.messageAdapter;
        if (messageAdapter == null || (selectedItems = messageAdapter.getSelectedItems()) == null) {
            return;
        }
        selectedItems.isEmpty();
    }
}