package com.epson.iprint.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.R;
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((int) R.layout.folder_content_layout);
        setActionBar(getStorageClient().getStorageServiceName(this), true);
        this.mEnumerator = getStorageClient().getEnumerator(this);
        this.mFolderStack = new Stack<>();
        this.mListView = (ListView) findViewById(16908298);
        this.mListView.setOnItemClickListener(new StorageItemClickListener());
        this.mListView.setCacheColorHint(0);
        try {
            this.mPrintLog = (PrintLog) getIntent().getSerializableExtra("print_log");
        } catch (ClassCastException unused) {
        }
        if (this.mPrintLog == null) {
            this.mPrintLog = new PrintLog();
        }
    }

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

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

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

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

    private void onUpdateProcessView() {
        if (this.mListView.getAdapter() != null) {
            return;
        }
        if (isConnected()) {
            StorageItem rootItem = getEnumerator().getRootItem();
            this.mFolderStack = new Stack<>();
            this.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();
            }
            this.mIsDownloadInterruption = false;
        }
    }

    class DownloadTask extends AsyncTaskExecutor<Void, Void, Void> {
        StorageItem item = null;
        String localPath = null;
        StorageActivity.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, this.item, this.localPath);
            C09241 r0 = downloader.isCancelable() ? new StorageActivity.CancelRequestCallback() {
                public void onCancelRequest(Intent intent) {
                    downloader.cancel();
                }
            } : null;
            this.progress = new StorageActivity.OverlayProgress();
            this.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) {
                this.error = processError;
            }

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

        DownloadTask(StorageItem storageItem) {
            this.item = storageItem;
            this.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.this.mFolderStack.size();
                if (size > 1) {
                    StorageItem storageItem = (StorageItem) StorageProcessDownloadActivity.this.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.this.mListView.setAdapter(new StorageItemAdapter(EnumerateTask.this.enumeratedItems));
                        } else if (processError != StorageServiceClient.ProcessError.CANCELED) {
                            StorageProcessDownloadActivity.this.showErrorDialog((int) 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.this.mListView.getAdapter();
                            if (storageItemAdapter != null) {
                                storageItemAdapter.addLoaedMoreItems(list);
                                storageItemAdapter.notifyDataSetChanged();
                            }
                        } else if (processError != StorageServiceClient.ProcessError.CANCELED) {
                            StorageProcessDownloadActivity.this.showErrorDialog((int) R.string.unknow_error_mes);
                        }
                        StorageProcessDownloadActivity.this.taskInvoked(false);
                        EnumerateTask.this.progress.dismiss();
                    }
                });
            }
        };
        StorageActivity.OverlayProgress progress = new StorageActivity.OverlayProgress();

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

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

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

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

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

    private void itemClick(int i) {
        this.mIsDownloading = true;
        if (isConnected()) {
            this.task = null;
            StorageItem storageItem = (StorageItem) this.mListView.getItemAtPosition(i);
            if (storageItem.type == StorageItem.ItemType.DIRECTORY) {
                if (storageItem.name.equals("..")) {
                    this.mFolderStack.pop();
                } else if (!storageItem.path.equals(((StorageItem) this.mFolderStack.lastElement()).path)) {
                    this.mFolderStack.push(storageItem);
                }
                this.task = new EnumerateTask(storageItem);
                int i2 = storageItem.mLoggerInfo;
            } else if (storageItem.type == StorageItem.ItemType.LOADMORE) {
                this.task = new EnumerateTask(storageItem);
            } else {
                this.task = new DownloadTask(storageItem);
            }
            AsyncTaskExecutor<Void, Void, Void> asyncTaskExecutor = this.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 = this.storageItems.get(i);
            View view2 = this.viewCache.get(storageItem);
            if (view2 == null) {
                view2 = this.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;
                }
                this.viewCache.put(storageItem, view2);
            }
            return view2;
        }

        StorageItemAdapter(List<StorageItem> list) {
            super(StorageProcessDownloadActivity.this.getBaseContext(), R.layout.file_list_item, list);
            this.layoutInflater = (LayoutInflater) StorageProcessDownloadActivity.this.getBaseContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE);
            this.storageItems = list;
            this.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(8);
            } else {
                imageView.setImageResource(i);
                imageView.setVisibility(0);
            }
            ImageView imageView2 = (ImageView) view.findViewById(R.id.browse_folder);
            if (i2 == -12345) {
                imageView2.setVisibility(8);
                return;
            }
            imageView2.setImageResource(i2);
            imageView2.setVisibility(0);
        }

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

        private void addLoaedMoreItems(List<StorageItem> list) {
            List<StorageItem> list2 = this.storageItems;
            list2.remove(list2.size() - 1);
            this.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) this.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 (this.mEnumerator == null) {
            this.mEnumerator = getStorageClient().getEnumerator(this);
        }
        return this.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;
    }
}
