package epson.print.storage.box;

import android.app.Activity;
import android.content.Context;



import com.box.androidsdk.content.BoxApiFile;
import com.box.androidsdk.content.BoxApiFolder;
import com.box.androidsdk.content.BoxApiSearch;
import com.box.androidsdk.content.BoxConfig;
import com.box.androidsdk.content.BoxConstants;
import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.auth.BoxAuthentication;
import com.box.androidsdk.content.models.BoxEntity;
import com.box.androidsdk.content.models.BoxError;
import com.box.androidsdk.content.models.BoxFile;
import com.box.androidsdk.content.models.BoxFolder;
import com.box.androidsdk.content.models.BoxItem;
import com.box.androidsdk.content.models.BoxIteratorItems;
import com.box.androidsdk.content.models.BoxSession;
import com.epson.iprint.storage.SecureKeyStore;
import com.epson.iprint.storage.StorageItem;
import com.epson.iprint.storage.StorageServiceClient;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;


import epson.print.IprintApplication;

public class BoxNetClient extends StorageServiceClient {
    private static BoxNetClient sBoxClient;
    private BoxApiFile mBoxApiFile;
    private BoxApiFolder mBoxApiFolder;
    private BoxSession mBoxSession;

    public boolean isSupportedUploadType(StorageServiceClient.UploadFileType uploadFileType) {
        return false;
    }

    public static synchronized BoxNetClient getInstance() {
        BoxNetClient boxNetClient;
        synchronized (BoxNetClient.class) {
            if (sBoxClient == null) {
                sBoxClient = new BoxNetClient();
            }
            boxNetClient = sBoxClient;
        }
        return boxNetClient;
    }

    private BoxNetClient() {
        BoxAuthStorage boxAuthStorage = new BoxAuthStorage();
        BoxAuthStorage.deleteOldData();
        BoxAuthentication.getInstance().setAuthStorage(boxAuthStorage);
        configureClient();
        initSession();
        if (isSignedIn(IprintApplication.getInstance())) {
            setLoginStatus(true);
        }
    }

    private void configureClient() {
        SecureKeyStore secureKeyStore = new SecureKeyStore();
        IprintApplication instance = IprintApplication.getInstance();
        BoxConfig.CLIENT_ID = secureKeyStore.getApiKeyC(instance);
        BoxConfig.CLIENT_SECRET = secureKeyStore.getSecKeyC(instance);
    }

    public StorageServiceClient.Uploader getUploader(Context context, StorageServiceClient.UploadFileType uploadFileType, final String str, final String str2) {
        return new StorageServiceClient.Uploader() {
            public boolean isCancelable() {
                return false;
            }

            public void start(StorageServiceClient.UploadCompletion uploadCompletion) {
                new UploadThread(uploadCompletion, str, str2).start();
            }
        };
    }

    public StorageServiceClient.Downloader getDownloader(Context context, final StorageItem storageItem, final String str) {
        if (storageItem == null || str == null) {
            return null;
        }
        return new StorageServiceClient.Downloader() {
            private DownloadThread mDownloadThread;

            public boolean isCancelable() {
                return true;
            }

            public void start(StorageServiceClient.DownloadCompletion downloadCompletion) {
                if (downloadCompletion != null) {
                    synchronized (this) {
                        mDownloadThread = new DownloadThread(downloadCompletion, storageItem, str);
                    }
                    mDownloadThread.start();
                }
            }

            public void cancel() {
                synchronized (this) {
                    if (mDownloadThread != null) {
                        mDownloadThread.cancel();
                    }
                }
            }
        };
    }

    @NonNull
    public StorageServiceClient.Enumerator getEnumerator(Context context) {
        return new StorageServiceClient.Enumerator() {
            @NonNull
            public StorageItem getRootItem() {
                return new StorageItem("", BoxConstants.ROOT_FOLDER_ID, StorageItem.ItemType.DIRECTORY);
            }

            public void enumerate(StorageItem storageItem, StorageServiceClient.EnumerateCompletion enumerateCompletion) {
                if (storageItem != null && enumerateCompletion != null) {
                    String str = storageItem.path;
                    if (str == null) {
                        str = BoxConstants.ROOT_FOLDER_ID;
                    }
                    new ListThread(enumerateCompletion, str).start();
                }
            }
        };
    }

    public boolean isSignedIn(Context context) {
        if (context == null || mBoxSession == null || BoxAuthentication.getInstance().getLastAuthenticatedUserId(context) == null) {
            return false;
        }
        return true;
    }

    public boolean revokeSignedInData(@NonNull Activity activity) {
        activity.startActivity(BoxNetSignInActivity.getLogoutIntent(activity));
        return true;
    }

    public String getStorageServiceName(Context context) {
        return context.getString(R.string.box_net);
    }

    public void boxLogout() {
        try {
            mBoxSession.logout().get();
        } catch (InterruptedException | ExecutionException unused) {
        }
    }

    public void initSession() {
        mBoxSession = new BoxSession((Context) IprintApplication.getInstance());
    }

    public void setSessionAuthListener(@Nullable BoxAuthentication.AuthListener authListener) {
        mBoxSession.setSessionAuthListener(authListener);
    }

    public void authenticate() {
        BoxSession boxSession = mBoxSession;
        if (boxSession != null) {
            boxSession.authenticate(IprintApplication.getInstance());
            return;
        }
        throw new IllegalStateException();
    }

    public void setLoginStatus(boolean z) {
        if (z) {
            BoxSession boxSession = mBoxSession;
            if (boxSession != null) {
                mBoxApiFolder = new BoxApiFolder(boxSession);
                mBoxApiFile = new BoxApiFile(mBoxSession);
                return;
            }
            return;
        }
        mBoxApiFolder = null;
        mBoxApiFile = null;
    }

    /* JADX WARNING: Code restructure failed: missing block: B:11:?, code lost:
        r0.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:12:0x001d, code lost:
        r5 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:13:0x001e, code lost:
        r3.addSuppressed(r5);
     */
    /* JADX WARNING: Code restructure failed: missing block: B:14:0x0022, code lost:
        r0.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:5:0x0013, code lost:
        r4 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:9:0x0017, code lost:
        if (r3 != null) goto L_0x0019;
     */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    private void uploadFile(@android.support.annotation.NonNull File r3, @android.support.annotation.NonNull String r4, String r5) throws IOException, com.box.androidsdk.content.BoxException {
        /*
            r2 = this;
            java.io.FileInputStream r0 = new java.io.FileInputStream
            r0.<init>(r3)
            r3 = 0
            com.box.androidsdk.content.BoxApiFile r1 = r2.mBoxApiFile     // Catch:{ Throwable -> 0x0015 }
            com.box.androidsdk.content.requests.BoxRequestsFile$UploadFile r4 = r1.getUploadRequest(r0, r4, r5)     // Catch:{ Throwable -> 0x0015 }
            r4.send()     // Catch:{ Throwable -> 0x0015 }
            r0.close()
            return
        L_0x0013:
            r4 = move-exception
            goto L_0x0017
        L_0x0015:
            r3 = move-exception
            throw r3     // Catch:{ all -> 0x0013 }
        L_0x0017:
            if (r3 == 0) goto L_0x0022
            r0.close()     // Catch:{ Throwable -> 0x001d }
            goto L_0x0025
        L_0x001d:
            r5 = move-exception
            r3.addSuppressed(r5)
            goto L_0x0025
        L_0x0022:
            r0.close()
        L_0x0025:
            throw r4
        */
        throw new UnsupportedOperationException("Method not decompiled: com.epson.iprint.storage.box.BoxNetClient.uploadFile(java.io.File, java.lang.String, java.lang.String):void");
    }

    /* JADX WARNING: Code restructure failed: missing block: B:11:?, code lost:
        r0.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:12:0x0021, code lost:
        r0 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:13:0x0022, code lost:
        r3.addSuppressed(r0);
     */
    /* JADX WARNING: Code restructure failed: missing block: B:14:0x0026, code lost:
        r0.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:5:0x0017, code lost:
        r4 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:9:0x001b, code lost:
        if (r3 != null) goto L_0x001d;
     */
    /* Code decompiled incorrectly, please refer to instructions dump. */
    private void uploadNewVersion(@android.support.annotation.NonNull File r3, @android.support.annotation.NonNull com.box.androidsdk.content.models.BoxFile r4) throws IOException, com.box.androidsdk.content.BoxException {
        /*
            r2 = this;
            java.io.FileInputStream r0 = new java.io.FileInputStream
            r0.<init>(r3)
            r3 = 0
            com.box.androidsdk.content.BoxApiFile r1 = r2.mBoxApiFile     // Catch:{ Throwable -> 0x0019 }
            java.lang.String r4 = r4.getId()     // Catch:{ Throwable -> 0x0019 }
            com.box.androidsdk.content.requests.BoxRequestsFile$UploadNewVersion r4 = r1.getUploadNewVersionRequest((java.io.InputStream) r0, (java.lang.String) r4)     // Catch:{ Throwable -> 0x0019 }
            r4.send()     // Catch:{ Throwable -> 0x0019 }
            r0.close()
            return
        L_0x0017:
            r4 = move-exception
            goto L_0x001b
        L_0x0019:
            r3 = move-exception
            throw r3     // Catch:{ all -> 0x0017 }
        L_0x001b:
            if (r3 == 0) goto L_0x0026
            r0.close()     // Catch:{ Throwable -> 0x0021 }
            goto L_0x0029
        L_0x0021:
            r0 = move-exception
            r3.addSuppressed(r0)
            goto L_0x0029
        L_0x0026:
            r0.close()
        L_0x0029:
            throw r4
        */
        throw new UnsupportedOperationException("Method not decompiled: com.epson.iprint.storage.box.BoxNetClient.uploadNewVersion(java.io.File, com.box.androidsdk.content.models.BoxFile):void");
    }

    private void uploadFileToFolder(@NonNull File file, @NonNull String str, @NonNull String str2) throws BoxException, IOException {
        if (mBoxSession != null) {
            String findOrCreateFolder = findOrCreateFolder(str);
            if (findOrCreateFolder != null) {
                uploadOrUpdate(file, str2, findOrCreateFolder);
                return;
            }
            throw new IOException("box folder can not create");
        }
        throw new IOException("Box session not initialized");
    }

    @Nullable
    private String findOrCreateFolder(@NonNull String str) throws BoxException {
        String searchRootFolder = searchRootFolder(str);
        if (searchRootFolder != null) {
            return searchRootFolder;
        }
        BoxFolder createFolder = createFolder(str);
        if (createFolder == null) {
            return null;
        }
        return createFolder.getId();
    }

    @Nullable
    private String searchFolderInRoot(@NonNull String str) throws BoxException {
        String str2 = "^" + str.replaceFirst(" .$", "");
        BoxApiSearch boxApiSearch = new BoxApiSearch(mBoxSession);
        int i = 0;
        while (true) {
            Iterator it = ((BoxIteratorItems) boxApiSearch.getSearchRequest(str2).setOffset(i).setLimit(3).limitType(BoxFolder.TYPE).limitAncestorFolderIds(new String[]{BoxConstants.ROOT_FOLDER_ID}).send()).iterator();
            if (!it.hasNext()) {
                return null;
            }
            while (it.hasNext()) {
                BoxItem boxItem = (BoxItem) it.next();
                if (str.equals(boxItem.getName())) {
                    return boxItem.getId();
                }
            }
            i += 3;
        }
    }

    @Nullable
    private String searchRootFolder(@NonNull String str) throws BoxException {
        Iterator it = ((BoxIteratorItems) mBoxApiFolder.getItemsRequest(BoxConstants.ROOT_FOLDER_ID).send()).iterator();
        while (it.hasNext()) {
            BoxItem boxItem = (BoxItem) it.next();
            if (str.equals(boxItem.getName()) && BoxFolder.TYPE.equals(boxItem.getType())) {
                return boxItem.getId();
            }
        }
        return null;
    }

    @Nullable
    private BoxFolder createFolder(@NonNull String str) throws BoxException {
        return (BoxFolder) mBoxApiFolder.getCreateRequest(BoxConstants.ROOT_FOLDER_ID, str).send();
    }

    private void uploadOrUpdate(@NonNull File file, @NonNull String str, @NonNull String str2) throws IOException, BoxException {
        try {
            uploadFile(file, str, str2);
        } catch (BoxException e) {
            BoxError asBoxError = e.getAsBoxError();
            if (asBoxError == null || asBoxError.getStatus().intValue() != 409) {
                throw e;
            }
            ArrayList<BoxEntity> conflicts = asBoxError.getContextInfo().getConflicts();
            if (conflicts == null || conflicts.size() != 1 || !(conflicts.get(0) instanceof BoxFile)) {
                throw e;
            }
            uploadNewVersion(file, (BoxFile) conflicts.get(0));
        }
    }

    /* access modifiers changed from: private */
    @NonNull
    public ArrayList<StorageItem> listFolder(@NonNull String str) throws BoxException {
        if (mBoxApiFolder != null) {
            ArrayList<StorageItem> arrayList = new ArrayList<>();
            Iterator it = ((BoxIteratorItems) mBoxApiFolder.getItemsRequest(str).send()).iterator();
            while (it.hasNext()) {
                BoxItem boxItem = (BoxItem) it.next();
                String name = boxItem.getName();
                String id = boxItem.getId();
                if (filterBoxItem(boxItem)) {
                    arrayList.add(new StorageItem(name, id, boxItem instanceof BoxFolder ? StorageItem.ItemType.DIRECTORY : StorageItem.ItemType.FILE));
                }
            }
            return arrayList;
        }
        throw new IllegalStateException();
    }

    private boolean filterBoxItem(@NonNull BoxItem boxItem) {
        return (boxItem instanceof BoxFolder) || StorageServiceClient.isPrintableFilename(boxItem.getName());
    }

    private void downloadFile(@NonNull String str, @NonNull String str2) throws IOException, BoxException {
        if (mBoxApiFile != null) {
            File file = new File(str2);
            file.createNewFile();
            mBoxApiFile.getDownloadRequest(file, str).send();
            return;
        }
        throw new IllegalStateException();
    }

    private static class ListThread extends Thread {
        private final String mBaseFolderId;
        private final BoxNetClient mBoxClient;
        private final StorageServiceClient.EnumerateCompletion mCompleteListener;

        private ListThread(@NonNull BoxNetClient boxNetClient, @NonNull StorageServiceClient.EnumerateCompletion enumerateCompletion, @NonNull String str) {
            super("list-box");
            mBoxClient = boxNetClient;
            mCompleteListener = enumerateCompletion;
            mBaseFolderId = str;
        }

        public void run() {
            try {
                mCompleteListener.onEnumerateComplete(mBoxClient.listFolder(mBaseFolderId), StorageServiceClient.ProcessError.NONE);
            } catch (BoxException unused) {
                mCompleteListener.onEnumerateComplete((List<StorageItem>) null, StorageServiceClient.ProcessError.ERROR);
            }
        }
    }

    private static class DownloadThread extends Thread {
        private final BoxNetClient mBoxClient;
        private volatile boolean mCanceled;
        private final StorageServiceClient.DownloadCompletion mDownloadEndListener;
        private final String mLocalPath;
        private final StorageItem mOnlineStorageItem;

        private DownloadThread(@NonNull BoxNetClient boxNetClient, @NonNull StorageServiceClient.DownloadCompletion downloadCompletion, @NonNull StorageItem storageItem, @NonNull String str) {
            super("download-box");
            mBoxClient = boxNetClient;
            mDownloadEndListener = downloadCompletion;
            mOnlineStorageItem = storageItem;
            mLocalPath = str;
            mCanceled = false;
        }

        public void run() {
            try {
                mBoxClient.downloadFile(mOnlineStorageItem.path, mLocalPath);
                if (mCanceled) {
                    mDownloadEndListener.onDownloadComplete((StorageItem) null, (String) null, StorageServiceClient.ProcessError.CANCELED);
                } else {
                    mDownloadEndListener.onDownloadComplete(mOnlineStorageItem, mLocalPath, StorageServiceClient.ProcessError.NONE);
                }
            } catch (BoxException | IOException unused) {
                if (mCanceled) {
                    mDownloadEndListener.onDownloadComplete((StorageItem) null, (String) null, StorageServiceClient.ProcessError.CANCELED);
                } else {
                    mDownloadEndListener.onDownloadComplete((StorageItem) null, (String) null, StorageServiceClient.ProcessError.ERROR);
                }
            }
        }

        public void cancel() {
            mCanceled = true;
        }
    }

    private static class UploadThread extends Thread {
        private final BoxNetClient mBoxClient;
        private final String mOrigLocalFilePath;
        private final StorageServiceClient.UploadCompletion mUploadEndListener;
        private final String mUploadOnlineName;

        private UploadThread(@NonNull BoxNetClient boxNetClient, @NonNull StorageServiceClient.UploadCompletion uploadCompletion, @NonNull String str, @NonNull String str2) {
            super("upload-box");
            mBoxClient = boxNetClient;
            mUploadEndListener = uploadCompletion;
            mOrigLocalFilePath = str;
            mUploadOnlineName = str2;
        }

        public void run() {
            try {
                mBoxClient.uploadFileToFolder(new File(mOrigLocalFilePath), "Epson iPrint", mUploadOnlineName);
                mUploadEndListener.onUploadComplete(mOrigLocalFilePath, mUploadOnlineName, StorageServiceClient.ProcessError.NONE);
            } catch (BoxException | IOException unused) {
                mUploadEndListener.onUploadComplete((String) null, (String) null, StorageServiceClient.ProcessError.ERROR);
            }
        }
    }
}
