package epson.print.storage;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.epson.iprint.prtlogger.PrintLog;

import org.opencv.videoio.Videoio;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

import epson.common.Utils;
import epson.print.ActivityDocsPrintPreview;
import epson.print.ActivityPrintWeb;
import epson.print.ActivityViewImageSelect;
import epson.print.CommonDefine;
import epson.print.Util.AsyncTaskExecutor;

public class StorageProcessDownloadActivity extends StorageProcessActivity {
    public static final String PARAM_KEY_ONLINE_STORAGE_PRINT_LOG = "print_log";
    private final String DOWNLOADED_FILE_PATH = "Downloaded.File.Path";
    private final String DOWNLOAD_PREFERENCE = "StorageProcessDownloadActivity.Preference";
    private final String ITEMNAME_PARENT = "..";
    private final int REQUEST_CODE_DELETE_DOWNLOADED_FILE = 0;
    private StorageServiceClient.Enumerator mEnumerator;
    private Stack<StorageItem> mFolderStack;
    private boolean mIsDownloadInterruption = false;
    private boolean mIsDownloading = false;
    private ListView mListView;
    private int mPosition = 0;
    private PrintLog mPrintLog;
    AsyncTaskExecutor<Void, Void, Void> task = null;

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.folder_content_layout);
        setActionBar(getStorageClient().getStorageServiceName(this), true);
        mEnumerator = getStorageClient().getEnumerator(this);
        mFolderStack = new Stack<>();
        mListView = (ListView) findViewById(16908298);
        mListView.setOnItemClickListener(new StorageItemClickListener());
        mListView.setCacheColorHint(0);
        try {
            mPrintLog = (PrintLog) getIntent().getSerializableExtra("print_log");
        } catch (ClassCastException unused) {
        }
        if (mPrintLog == null) {
            mPrintLog = new PrintLog();
        }
    }

    public void onBackPressed() {
        StorageItemAdapter storageItemAdapter = (StorageItemAdapter) mListView.getAdapter();
        if (storageItemAdapter == null) {
            finish();
        } else if (storageItemAdapter.areAllItemsEnabled()) {
            if (mFolderStack.size() > 1) {
                mFolderStack.pop();
                if (isConnected()) {
                    new EnumerateTask(mFolderStack.peek()).executeOnExecutor(new Void[0]);
                } else {
                    showConnectionError();
                }
            } else {
                finish();
            }
        }
    }

    private void onSignInStatus(SignInStatus signInStatus) {
        if (signInStatus == SignInStatus.SIGNED_IN) {
            mListView.setVisibility(View.VISIBLE);
            return;
        }
        mListView.setVisibility(4);
        mListView.setAdapter((ListAdapter) null);
        StorageServiceClient.Enumerator enumerator = mEnumerator;
        if (enumerator != null) {
            enumerator.cleanUpResources();
        }
    }

    protected void onStop() {
        super.onStop();
        if (mIsDownloading && Build.VERSION.SDK_INT >= 29) {
            mIsDownloadInterruption = true;
            task.cancel(false);
        }
    }

    protected void onRestart() {
        super.onRestart();
        if (mIsDownloadInterruption && !mIsDownloading) {
            itemClick(mPosition);
        }
        mIsDownloadInterruption = false;
    }

    private void onUpdateProcessView() {
        if (mListView.getAdapter() != null) {
            return;
        }
        if (isConnected()) {
            StorageItem rootItem = getEnumerator().getRootItem();
            mFolderStack = new Stack<>();
            mFolderStack.push(rootItem);
            new EnumerateTask(rootItem).executeOnExecutor(new Void[0]);
            return;
        }
        showConnectionError();
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        if (i == 0) {
            String fetchDownloadedFilePath = fetchDownloadedFilePath();
            if (fetchDownloadedFilePath != null) {
                new File(fetchDownloadedFilePath).delete();
            }
            mIsDownloadInterruption = false;
        }
    }

    class DownloadTask extends AsyncTaskExecutor<Void, Void, Void> {
        StorageItem item = null;
        String localPath = null;
        OverlayProgress progress = null;

        protected void onPreExecute() {
            StorageProcessDownloadActivity.this.taskInvoked(true);
        }

        protected Void doInBackground(Void... voidArr) {
            final StorageServiceClient.Downloader downloader = StorageProcessDownloadActivity.this.getStorageClient().getDownloader(StorageProcessDownloadActivity.this, item, localPath);
            C09241 r0 = downloader.isCancelable() ? new CancelRequestCallback() {
                public void onCancelRequest(Intent intent) {
                    downloader.cancel();
                }
            } : null;
            progress = new OverlayProgress();
            progress.show(StorageProcessDownloadActivity.this.getString(R.string.downloading_notification), r0);
            downloader.start(new StorageServiceClient.DownloadCompletion() {
                public void onDownloadComplete(StorageItem storageItem, String str, StorageServiceClient.ProcessError processError) {
                    if (str != null) {
                        DownloadTask.this.localPath = str;
                    }
                    StorageProcessDownloadActivity.this.runOnUiThread(new DownloadedRun(processError));
                }
            });
            return null;
        }

        class DownloadedRun implements Runnable {
            StorageServiceClient.ProcessError error;

            DownloadedRun(StorageServiceClient.ProcessError processError) {
                error = processError;
            }

            public void run() {
                boolean unused = StorageProcessDownloadActivity.mIsDownloading = false;
                if (this.error == StorageServiceClient.ProcessError.NONE) {
                    StorageProcessDownloadActivity storageProcessDownloadActivity = StorageProcessDownloadActivity.this;
                    Intent previewIntent = StorageProcessDownloadActivity.getPreviewIntent(DownloadTask.this.localPath, storageProcessDownloadActivity, StorageProcessDownloadActivity.mPrintLog);
                    previewIntent.setFlags(Videoio.CAP_INTELPERC_IMAGE_GENERATOR);
                    StorageProcessDownloadActivity.this.saveDownloadedFilePath(DownloadTask.this.localPath);
                    if (!StorageProcessDownloadActivity.mIsDownloadInterruption) {
                        storageProcessDownloadActivity.startActivityForResult(previewIntent, 0);
                    }
                } else if (this.error != StorageServiceClient.ProcessError.CANCELED) {
                    StorageProcessDownloadActivity.this.showErrorDialog(R.string.download_error_mes);
                }
                StorageProcessDownloadActivity.this.taskInvoked(false);
                DownloadTask.this.progress.dismiss();
            }
        }

        DownloadTask(StorageItem storageItem) {
            item = storageItem;
            localPath = StorageProcessDownloadActivity.this.getStorageClient().getDownloadLocalPath(StorageProcessDownloadActivity.this, storageItem);
        }
    }

    public static Intent getPreviewIntent(@NonNull String str, @NonNull Context context, @NonNull PrintLog printLog) {
        Intent intent = new Intent();
        intent.putExtra("from", 4);
        if (StorageItem.endsWith(str, CommonDefine.FileType_PDF) || Utils.isGConvertFile(str)) {
            intent.putExtra(CommonDefine.SEND_DOCUMENT_VIEW, str);
            intent.setClass(context, ActivityDocsPrintPreview.class);
            printLog.originalFileExtension = PrintLog.getFileExtension(str);
            intent.putExtra("print_log", printLog);
        } else if (Utils.isPhotoFile(str)) {
            intent.setAction("android.intent.action.SEND");
            intent.putExtra("android.intent.extra.STREAM", Uri.parse(str));
            intent.setType(Utils.getMimeExt(str));
            intent.putExtra(CommonDefine.STYPE, true);
            intent.setClass(context, ActivityViewImageSelect.class);
            intent.putExtra(ActivityViewImageSelect.PARAMS_KEY_FROM_EPSON, true);
            printLog.originalFileExtension = PrintLog.getFileExtension(str);
            intent.putExtra("print_log", printLog);
        } else {
            ArrayList arrayList = new ArrayList();
            arrayList.add(str);
            intent.putStringArrayListExtra("print_web", arrayList);
            intent.putExtra(CommonDefine.STYPE, true);
            intent.setClass(context, ActivityPrintWeb.class);
            printLog.originalFileExtension = PrintLog.getFileExtension(str);
            intent.putExtra("print_log", printLog);
        }
        return intent;
    }

    class EnumerateTask extends AsyncTaskExecutor<Void, Void, Void> {
        List<StorageItem> enumeratedItems;
        StorageItem item;
        final StorageServiceClient.EnumerateCompletion onEnumerated = new StorageServiceClient.EnumerateCompletion() {
            public void onEnumerateComplete(List<StorageItem> list, final StorageServiceClient.ProcessError processError) {
                EnumerateTask enumerateTask = EnumerateTask.this;
                enumerateTask.enumeratedItems = list;
                int size = StorageProcessDownloadActivity.mFolderStack.size();
                if (size > 1) {
                    StorageItem storageItem = (StorageItem) StorageProcessDownloadActivity.mFolderStack.get(size - 2);
                    StorageItem storageItem2 = new StorageItem("..");
                    storageItem2.path = storageItem.path;
                    storageItem2.type = StorageItem.ItemType.DIRECTORY;
                    storageItem2.userInfo = storageItem.userInfo;
                    if (EnumerateTask.this.enumeratedItems == null) {
                        EnumerateTask.this.enumeratedItems = new ArrayList();
                    }
                    EnumerateTask.this.enumeratedItems.add(0, storageItem2);
                }
                StorageProcessDownloadActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        if (processError == StorageServiceClient.ProcessError.NONE && EnumerateTask.this.enumeratedItems != null) {
                            StorageProcessDownloadActivity.mListView.setAdapter(new StorageItemAdapter(EnumerateTask.this.enumeratedItems));
                        } else if (processError != StorageServiceClient.ProcessError.CANCELED) {
                            StorageProcessDownloadActivity.this.showErrorDialog(R.string.unknow_error_mes);
                        }
                        StorageProcessDownloadActivity.this.taskInvoked(false);
                        EnumerateTask.this.progress.dismiss();
                    }
                });
            }
        };
        StorageServiceClient.EnumerateCompletion onLoadedMore = new StorageServiceClient.EnumerateCompletion() {
            public void onEnumerateComplete(final List<StorageItem> list, final StorageServiceClient.ProcessError processError) {
                StorageProcessDownloadActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        if (processError == StorageServiceClient.ProcessError.NONE) {
                            StorageItemAdapter storageItemAdapter = (StorageItemAdapter) StorageProcessDownloadActivity.mListView.getAdapter();
                            if (storageItemAdapter != null) {
                                storageItemAdapter.addLoaedMoreItems(list);
                                storageItemAdapter.notifyDataSetChanged();
                            }
                        } else if (processError != StorageServiceClient.ProcessError.CANCELED) {
                            StorageProcessDownloadActivity.this.showErrorDialog(R.string.unknow_error_mes);
                        }
                        StorageProcessDownloadActivity.this.taskInvoked(false);
                        EnumerateTask.this.progress.dismiss();
                    }
                });
            }
        };
        OverlayProgress progress = new OverlayProgress();

        protected void onPreExecute() {
            StorageProcessDownloadActivity.this.taskInvoked(true);
        }

        protected Void doInBackground(Void... voidArr) {
            boolean isNeedSignin = StorageProcessDownloadActivity.this.getStorageClient().isNeedSignin();
            if (!isNeedSignin) {
                progress.show();
            }
            if (this.item.type == StorageItem.ItemType.LOADMORE) {
                StorageProcessDownloadActivity.this.getEnumerator().enumerate(this.item, onLoadedMore);
                return null;
            } else if (!isNeedSignin) {
                StorageProcessDownloadActivity.this.getEnumerator().enumerate(this.item, onEnumerated);
                return null;
            } else {
                StorageProcessDownloadActivity.this.getEnumerator().enumerate(this.item, onEnumerated, new StorageServiceClient.SigninCompletion() {
                    public void onSigninCompletion() {
                        EnumerateTask.this.progress.show((String) null, (CancelRequestCallback) null, false);
                    }
                });
                return null;
            }
        }

        EnumerateTask(StorageItem storageItem) {
            item = storageItem;
        }
    }

    private class StorageItemClickListener implements AdapterView.OnItemClickListener {
        private StorageItemClickListener() {
        }

        public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
            int unused = StorageProcessDownloadActivity.mPosition = i;
            StorageProcessDownloadActivity.this.itemClick(i);
        }
    }

    private void itemClick(int i) {
        mIsDownloading = true;
        if (isConnected()) {
            task = null;
            StorageItem storageItem = (StorageItem) mListView.getItemAtPosition(i);
            if (storageItem.type == StorageItem.ItemType.DIRECTORY) {
                if (storageItem.name.equals("..")) {
                    mFolderStack.pop();
                } else if (!storageItem.path.equals(((StorageItem) mFolderStack.lastElement()).path)) {
                    mFolderStack.push(storageItem);
                }
                task = new EnumerateTask(storageItem);
                int i2 = storageItem.mLoggerInfo;
            } else if (storageItem.type == StorageItem.ItemType.LOADMORE) {
                task = new EnumerateTask(storageItem);
            } else {
                task = new DownloadTask(storageItem);
            }
            AsyncTaskExecutor<Void, Void, Void> asyncTaskExecutor = task;
            if (asyncTaskExecutor != null) {
                asyncTaskExecutor.executeOnExecutor(new Void[0]);
                return;
            }
            return;
        }
        showConnectionError();
    }

    class StorageItemAdapter extends ArrayAdapter<StorageItem> {
        final int COMPONENT_GONE = -12345;
        LayoutInflater layoutInflater;
        List<StorageItem> storageItems;
        boolean taskRunningNow;
        HashMap<StorageItem, View> viewCache;

        public boolean areAllItemsEnabled() {
            return !this.taskRunningNow;
        }

        public boolean isEnabled(int i) {
            return areAllItemsEnabled();
        }

        @NonNull
        public View getView(int i, View view, @NonNull ViewGroup viewGroup) {
            StorageItem storageItem = storageItems.get(i);
            View view2 = viewCache.get(storageItem);
            if (view2 == null) {
                view2 = layoutInflater.inflate(R.layout.file_list_item, (ViewGroup) null);
                switch (storageItem.type) {
                    case DIRECTORY:
                        if (!storageItem.name.equals("..")) {
                            setViewComponents(view2, storageItem.name, R.drawable.folder, R.drawable.more);
                            break;
                        } else {
                            setViewComponents(view2, storageItem.name, R.drawable.parent_folder, R.drawable.more);
                            break;
                        }
                    case LOADMORE:
                        String str = storageItem.name;
                        if (str == null) {
                            str = StorageProcessDownloadActivity.this.getString(R.string.storage_item_load_more_photos);
                        }
                        setViewComponents(view2, str, -12345, -12345);
                        break;
                    case FILE:
                        setViewComponents(view2, storageItem.name, R.drawable.file, -12345);
                        break;
                    case PHOTO:
                        setViewComponents(view2, storageItem.name, R.drawable.image, -12345);
                        StorageProcessDownloadActivity.this.getEnumerator().setThumbnailInBackground(storageItem, getIconView(view2));
                        break;
                }
                viewCache.put(storageItem, view2);
            }
            return view2;
        }

        StorageItemAdapter(List<StorageItem> list) {
            super(StorageProcessDownloadActivity.this.getBaseContext(), R.layout.file_list_item, list);
            layoutInflater = (LayoutInflater) StorageProcessDownloadActivity.this.getBaseContext().getSystemService("layout_inflater");
            storageItems = list;
            viewCache = new HashMap<>();
        }

        private void setViewComponents(View view, String str, int i, int i2) {
            ((TextView) view.findViewById(R.id.file_folder_name)).setText(str);
            ImageView imageView = (ImageView) view.findViewById(R.id.file_folder_icon);
            if (i == -12345) {
                imageView.setVisibility(View.GONE);
            } else {
                imageView.setImageResource(i);
                imageView.setVisibility(View.VISIBLE);
            }
            ImageView imageView2 = (ImageView) view.findViewById(R.id.browse_folder);
            if (i2 == -12345) {
                imageView2.setVisibility(View.GONE);
                return;
            }
            imageView2.setImageResource(i2);
            imageView2.setVisibility(View.VISIBLE);
        }

        private void setTaskingStatus(boolean z) {
            taskRunningNow = z;
        }

        private void addLoaedMoreItems(List<StorageItem> list) {
            List<StorageItem> list2 = storageItems;
            list2.remove(list2.size() - 1);
            storageItems.addAll(list);
        }

        private ImageView getIconView(View view) {
            return (ImageView) view.findViewById(R.id.file_folder_icon);
        }
    }

    private void taskInvoked(boolean z) {
        StorageItemAdapter storageItemAdapter = (StorageItemAdapter) mListView.getAdapter();
        if (storageItemAdapter != null) {
            storageItemAdapter.setTaskingStatus(z);
        }
        boolean z2 = true;
        if (z) {
            z2 = false;
        }
        setSignInButtonEnabled(z2);
    }

    private void saveDownloadedFilePath(String str) {
        getSharedPreferences("StorageProcessDownloadActivity.Preference", 0).edit().putString("Downloaded.File.Path", str).apply();
    }

    private String fetchDownloadedFilePath() {
        return getSharedPreferences("StorageProcessDownloadActivity.Preference", 0).getString("Downloaded.File.Path", (String) null);
    }

    private StorageServiceClient.Enumerator getEnumerator() {
        if (mEnumerator == null) {
            mEnumerator = getStorageClient().getEnumerator(this);
        }
        return mEnumerator;
    }

    @NonNull
    public static Intent getStartIntent(@NonNull Context context, String str) {
        Intent intent = new Intent(context, StorageProcessDownloadActivity.class);
        PrintLog printLog = new PrintLog();
        printLog.uiRoute = getOnlineStorageUiRouteValue(str);
        intent.putExtra("print_log", printLog);
        setCommonExtra(intent, str);
        return intent;
    }

    private static int getOnlineStorageUiRouteValue(String str) {
        if (str == null) {
            return -1;
        }
        if (StorageServiceClient.STORAGE_BOX.equals(str)) {
            return PrintLog.PRINT_SOURCE_BOX;
        }
        if (StorageServiceClient.STORAGE_DROPBOX.equals(str)) {
            return PrintLog.PRINT_SOURCE_DROPBOX;
        }
        if (StorageServiceClient.STORAGE_EVERNOTE.equals(str)) {
            return 256;
        }
        if (StorageServiceClient.STORAGE_GOOGLEDRIVE.equals(str)) {
            return 257;
        }
        if (StorageServiceClient.STORAGE_ONEDRIVE.equals(str)) {
            return PrintLog.PRINT_SOURCE_ONEDRIVE;
        }
        return -1;
    }
}
