package com.epson.iprint.storage.gdrivev3;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;


import com.epson.iprint.storage.gdrivev3.DownloadTask;
import com.epson.iprint.storage.gdrivev3.DriveListTask;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.FileList;
import epson.print.CommonDefine;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;

public class GoogleDownloader {
    private static final String ROOT_ID = "root";
    private static final String TARGET_SCOPE = "https://www.googleapis.com/auth/drive";
    private final Drive mDrive;
    private final FolderManager mFolderManager = new FolderManager();

    public static String getTargetScope() {
        return "https://www.googleapis.com/auth/drive";
    }

    private GoogleDownloader(@NonNull Drive drive) {
        this.mDrive = drive;
    }

    public DownloadTask startDownload(@NonNull ActivityWrapper activityWrapper, @NonNull OnlineFile onlineFile, @NonNull DownloadTask.DownloadCompleteListener downloadCompleteListener) {
        DownloadTask downloadTask = new DownloadTask(activityWrapper.getActivity().getApplicationContext(), this, downloadCompleteListener);
        downloadTask.execute(new OnlineFile[]{onlineFile});
        return downloadTask;
    }

    public void startListTask(@Nullable OnlineFile onlineFile, @NonNull DriveListTask.ListTaskCompleteListener listTaskCompleteListener) {
        new DriveListTask(this, listTaskCompleteListener).execute(new OnlineFile[]{onlineFile});
    }

    public boolean isRootFolder() {
        return this.mFolderManager.isRootFolder();
    }

    @Nullable
    public OnlineFile downloadPdf(GoogleDriveFile googleDriveFile, File file) throws IOException {
        Throwable th;
        String id = googleDriveFile.getId();
        if (id != null) {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            try {
                this.mDrive.files().export(id, "application/pdf").executeMediaAndDownloadTo(fileOutputStream);
                fileOutputStream.close();
                return new DownloadFile(file.getPath(), "application/pdf");
            } catch (Throwable th2) {
                th.addSuppressed(th2);
            }
        } else {
            throw new IllegalStateException();
        }
        throw th;
    }

    /* JADX WARNING: Code restructure failed: missing block: B:12:?, code lost:
        r2.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:13:0x002f, code lost:
        if (r7 == null) goto L_0x0034;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:14:0x0031, code lost:
        r7.close();
     */
    /* JADX WARNING: Code restructure failed: missing block: B:15:0x0034, code lost:
        return r0;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:16:0x0035, code lost:
        r8 = th;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:17:0x0036, code lost:
        r9 = null;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:21:0x003a, code lost:
        r9 = move-exception;
     */
    /* JADX WARNING: Code restructure failed: missing block: B:22:0x003b, code lost:
        r5 = r9;
        r9 = r8;
        r8 = r5;
     */
    @android.support.annotation.Nullable
    /* Code decompiled incorrectly, please refer to instructions dump. */
    public com.epson.iprint.storage.gdrivev3.OnlineFile downloadFile(com.epson.iprint.storage.gdrivev3.OnlineFile r7, java.io.File r8, @android.support.annotation.NonNull com.epson.iprint.storage.gdrivev3.Canceller r9) throws java.io.IOException {
        /*
            r6 = this;
            com.epson.iprint.storage.gdrivev3.DownloadFile r0 = new com.epson.iprint.storage.gdrivev3.DownloadFile
            java.lang.String r1 = r8.getPath()
            java.lang.String r2 = r7.getMimeType()
            r0.<init>(r1, r2)
            java.io.InputStream r7 = r6.getFileInputStream(r7)
            r1 = 0
            java.io.FileOutputStream r2 = new java.io.FileOutputStream     // Catch:{ Throwable -> 0x004f }
            r2.<init>(r8)     // Catch:{ Throwable -> 0x004f }
            r8 = 1024(0x400, float:1.435E-42)
            byte[] r8 = new byte[r8]     // Catch:{ Throwable -> 0x0038, all -> 0x0035 }
        L_0x001b:
            int r3 = r7.read(r8)     // Catch:{ Throwable -> 0x0038, all -> 0x0035 }
            if (r3 < 0) goto L_0x002c
            boolean r4 = r9.canceled()     // Catch:{ Throwable -> 0x0038, all -> 0x0035 }
            if (r4 != 0) goto L_0x002c
            r4 = 0
            r2.write(r8, r4, r3)     // Catch:{ Throwable -> 0x0038, all -> 0x0035 }
            goto L_0x001b
        L_0x002c:
            r2.close()     // Catch:{ Throwable -> 0x004f }
            if (r7 == 0) goto L_0x0034
            r7.close()
        L_0x0034:
            return r0
        L_0x0035:
            r8 = move-exception
            r9 = r1
            goto L_0x003e
        L_0x0038:
            r8 = move-exception
            throw r8     // Catch:{ all -> 0x003a }
        L_0x003a:
            r9 = move-exception
            r5 = r9
            r9 = r8
            r8 = r5
        L_0x003e:
            if (r9 == 0) goto L_0x0049
            r2.close()     // Catch:{ Throwable -> 0x0044 }
            goto L_0x004c
        L_0x0044:
            r0 = move-exception
            r9.addSuppressed(r0)     // Catch:{ Throwable -> 0x004f }
            goto L_0x004c
        L_0x0049:
            r2.close()     // Catch:{ Throwable -> 0x004f }
        L_0x004c:
            throw r8     // Catch:{ Throwable -> 0x004f }
        L_0x004d:
            r8 = move-exception
            goto L_0x0052
        L_0x004f:
            r8 = move-exception
            r1 = r8
            throw r1     // Catch:{ all -> 0x004d }
        L_0x0052:
            if (r7 == 0) goto L_0x0062
            if (r1 == 0) goto L_0x005f
            r7.close()     // Catch:{ Throwable -> 0x005a }
            goto L_0x0062
        L_0x005a:
            r7 = move-exception
            r1.addSuppressed(r7)
            goto L_0x0062
        L_0x005f:
            r7.close()
        L_0x0062:
            throw r8
        */
        throw new UnsupportedOperationException("Method not decompiled: com.epson.iprint.storage.gdrivev3.GoogleDownloader.downloadFile(com.epson.iprint.storage.gdrivev3.OnlineFile, java.io.File, com.epson.iprint.storage.gdrivev3.Canceller):com.epson.iprint.storage.gdrivev3.OnlineFile");
    }

    @NonNull
    public static GoogleDownloader createGoogleDownloader(@NonNull Context context, @NonNull GoogleSignInAccount googleSignInAccount) {
        GoogleAccountCredential usingOAuth2 = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(getTargetScope()));
        usingOAuth2.setSelectedAccount(googleSignInAccount.getAccount());
        return new GoogleDownloader(new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), usingOAuth2).setApplicationName(getDriveApplicationName(context)).build());
    }

    public static String getDriveApplicationName(@NonNull Context context) {
        String appName = getAppName(context);
        return appName == null ? context.getPackageName() : appName;
    }

    private static String getAppName(@NonNull Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 128);
            String str = (String) packageInfo.applicationInfo.loadLabel(context.getPackageManager());
            if (packageInfo.versionName == null) {
                return str;
            }
            return str + CommonDefine.SLASH + packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException unused) {
            return null;
        }
    }

    @NonNull
    public ArrayList<OnlineFile> listFile(@Nullable OnlineFile onlineFile) throws IOException {
        Drive.Files files = this.mDrive.files();
        this.mFolderManager.changeCurrentFolder(onlineFile);
        String currentFolderId = this.mFolderManager.getCurrentFolderId();
        ArrayList<OnlineFile> arrayList = new ArrayList<>();
        String str = null;
        do {
            Drive.Files.List list = files.list();
            FileList fileList = (FileList) list.setQ("'" + currentFolderId + "' in parents and trashed = false and (mimeType contains 'image/' or mimeType contains 'application/' or mimeType contains 'text/')").setFields("nextPageToken, files(id, name, mimeType, trashed)").setPageToken(str).execute();
            if (!this.mFolderManager.isRootFolder()) {
                arrayList.add(new ParentFolder());
            }
            for (com.google.api.services.drive.model.File googleDriveFile : fileList.getFiles()) {
                arrayList.add(new GoogleDriveFile(googleDriveFile));
            }
            str = fileList.getNextPageToken();
        } while (str != null);
        return arrayList;
    }

    private InputStream getFileInputStream(@NonNull OnlineFile onlineFile) throws IOException {
        String id = onlineFile.getId();
        if (id != null) {
            return this.mDrive.files().get(id).executeMediaAsInputStream();
        }
        throw new IOException("getId() return null");
    }

    private static class FolderManager {
        private OnlineFile mCurrentFolder = null;
        private final LinkedList<OnlineFile> mParentDirList = new LinkedList<>();

        FolderManager() {
        }

        /* access modifiers changed from: private */
        public void changeCurrentFolder(@Nullable OnlineFile onlineFile) {
            if (onlineFile == null || !onlineFile.isFolder()) {
                return;
            }
            if (onlineFile instanceof ParentFolder) {
                gotoParent();
                return;
            }
            OnlineFile onlineFile2 = this.mCurrentFolder;
            if (onlineFile2 != null) {
                this.mParentDirList.push(onlineFile2);
            }
            this.mCurrentFolder = onlineFile;
        }

        private void gotoRoot() {
            this.mParentDirList.clear();
            this.mCurrentFolder = null;
        }

        private void gotoParent() {
            if (this.mParentDirList.isEmpty()) {
                this.mCurrentFolder = null;
                gotoRoot();
                return;
            }
            OnlineFile pop = this.mParentDirList.pop();
            if (pop == null) {
                gotoRoot();
                return;
            }
            this.mCurrentFolder = pop;
            this.mCurrentFolder.getId();
        }

        private String getCurrentFolderId() {
            OnlineFile onlineFile = this.mCurrentFolder;
            if (onlineFile == null) {
                return GoogleDownloader.ROOT_ID;
            }
            return onlineFile.getId();
        }

        /* access modifiers changed from: private */
        public boolean isRootFolder() {
            return this.mCurrentFolder == null;
        }
    }
}
