package epson.print.storage.gdrivev3;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;

import java.io.File;
import java.io.IOException;

import epson.common.ExternalFileUtils;
import epson.common.Utils;
import epson.print.CommonDefine;

public class DownloadTask extends AsyncTask<OnlineFile, Void, OnlineFile> implements Canceller {
    private static final String DOWNLOAD_TMP_FILE_NAME_BODY = "google_v3";
    @SuppressLint({"StaticFieldLeak"})
    private final Context mApplicationContext;
    private volatile boolean mDownloadCancelled = false;
    private final DownloadCompleteListener mDownloadCompleteListener;
    private volatile File mDownloadFile;
    private final GoogleDownloader mMyDrive;
    private Exception mThreadException;

    public interface DownloadCompleteListener {
        void onDownloadComplete(boolean z, @Nullable String str);
    }

    DownloadTask(@NonNull Context context, @NonNull GoogleDownloader googleDownloader, @NonNull DownloadCompleteListener downloadCompleteListener) {
        mApplicationContext = context;
        mMyDrive = googleDownloader;
        mDownloadCompleteListener = downloadCompleteListener;
        mDownloadFile = null;
    }

    protected OnlineFile doInBackground(OnlineFile... onlineFileArr) {
        GoogleDriveFile googleDriveFile;
        if (onlineFileArr == null || (googleDriveFile = onlineFileArr[0]) == null) {
            return null;
        }
        try {
            if (!(googleDriveFile instanceof GoogleDriveFile) || !googleDriveFile.isGoogleDocuments()) {
                File outFile = getOutFile(mApplicationContext, getExtensionFromMimeType((OnlineFile) googleDriveFile));
                mDownloadFile = outFile;
                if (outFile == null) {
                    return null;
                }
                return mMyDrive.downloadFile(googleDriveFile, outFile, this);
            }
            File outFile2 = getOutFile(mApplicationContext, CommonDefine.FileType_PDF);
            mDownloadFile = outFile2;
            if (outFile2 == null) {
                return null;
            }
            return mMyDrive.downloadPdf(googleDriveFile, outFile2);
        } catch (Exception e) {
            mThreadException = e;
            return null;
        }
    }

    @VisibleForTesting
    @NonNull
    static String getExtensionFromMimeType(OnlineFile onlineFile) {
        if (onlineFile == null) {
            return "";
        }
        String extensionFromMimeType = getExtensionFromMimeType(onlineFile.getMimeType());
        return extensionFromMimeType.isEmpty() ? getExtensionFromMimeType(Utils.getMimeType(onlineFile.getName())) : extensionFromMimeType;
    }

    @NonNull
    private static String getExtensionFromMimeType(String str) {
        String mimeExt = Utils.getMimeExt(str);
        return mimeExt != null ? mimeExt : "";
    }

    protected void onPostExecute(OnlineFile onlineFile) {
        if (mDownloadCancelled) {
            mDownloadCompleteListener.onDownloadComplete(false, (String) null);
        }
        if (onlineFile != null) {
            String name = onlineFile.getName();
            if (name != null) {
                mDownloadCompleteListener.onDownloadComplete(false, name);
            } else {
                mDownloadCompleteListener.onDownloadComplete(true, (String) null);
            }
        } else {
            Exception exc = mThreadException;
            deleteDownloadFile();
            mDownloadCompleteListener.onDownloadComplete(true, (String) null);
        }
    }

    protected void onCancelled() {
        deleteDownloadFile();
        mDownloadCompleteListener.onDownloadComplete(false, (String) null);
    }

    public boolean canceled() {
        return mDownloadCancelled;
    }

    public void cancelTask() {
        mDownloadCancelled = true;
        cancel(true);
    }

    @Nullable
    private File getOutFile(@NonNull Context context, @NonNull String str) {
        try {
            File prepareOutDirectory = prepareOutDirectory(context);
            return new File(prepareOutDirectory, DOWNLOAD_TMP_FILE_NAME_BODY + str);
        } catch (IOException | SecurityException unused) {
            return null;
        }
    }

    @NonNull
    private File prepareOutDirectory(@NonNull Context context) throws IOException {
        File file = new File(ExternalFileUtils.getInstance(context).getDownloadDir());
        if (file.exists() || file.mkdirs()) {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File delete : listFiles) {
                    delete.delete();
                }
            }
            return file;
        }
        throw new IOException();
    }

    public void deleteDownloadFile() {
        if (mDownloadFile != null && mDownloadFile.exists()) {
            mDownloadFile.delete();
            mDownloadFile = null;
        }
    }
}
