package com.epson.iprint.apf;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.os.Environment;
import android.util.Log;

import com.epson.p007sd.common.apf.apflib;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.locks.ReentrantLock;

import epson.common.ExternalFileUtils;
import epson.common.ImageUtil;
import epson.print.CommonDefine;
import epson.print.EPImageUtil;
import epson.print.MyPrinter;
import epson.print.Util.BmpFileSize;

public class ApfAdapter {
    protected static final String APF_IMAGE_DIR = "apf_image";
    public static final String BMP_EXTENSION = ".bmp";
    protected static final String FILE_PREFIX_APF = "apf";
    protected static final String FILE_PREFIX_TMP1 = "tmp1_";
    protected static final String FILE_PREFIX_TMP2 = "tmp2_";
    protected static final ReentrantLock mApfLock = new ReentrantLock();
    protected File mApfImageDir = new File(ExternalFileUtils.getInstance(mApplicationContext).getCacheDir(), APF_IMAGE_DIR);
    protected Context mApplicationContext;

    public ApfAdapter(Context context) {
        mApplicationContext = context.getApplicationContext();
        ExternalFileUtils.getInstance(mApplicationContext).createTempFolder(mApfImageDir.getPath());
    }

    public static void clearDirectory(Context context) {
        deleteDirectory(new File(ExternalFileUtils.getInstance(context).getCacheDir(), APF_IMAGE_DIR));
    }

    public static void deleteDirectory(File file) {
        if (file.exists()) {
            if (!file.isDirectory()) {
                file.delete();
                return;
            }
            for (File file2 : file.listFiles()) {
                if (file2.isDirectory()) {
                    deleteDirectory(file2);
                }
                if (file2.exists()) {
                    file2.delete();
                }
            }
        }
    }

    public static int getExifRotationValue(String str) {
        try {
            return new ExifInterface(str).getAttributeInt(android.support.media.ExifInterface.TAG_ORIENTATION, 0);
        } catch (IOException unused) {
            return 0;
        }
    }

    public static File rotateWithExifValue(int i, File file, File file2) {
        EPImageUtil ePImageUtil = new EPImageUtil();
        if (i == 3) {
            ePImageUtil.rotate180Image(file.toString(), file2.toString());
            return file2;
        } else if (i == 6) {
            ePImageUtil.rotateR90Image(file.toString(), file2.toString());
            return file2;
        } else if (i != 8) {
            return file;
        } else {
            ePImageUtil.rotateR270Image(file.toString(), file2.toString());
            return file2;
        }
    }

    public String getApfResult(String str, int i, int i2, int i3) {
        String apfFilename = getApfFilename(str, i, i2, i3);
        if (canUseApfResult(apfFilename)) {
            return apfFilename;
        }
        try {
            mApfLock.lockInterruptibly();
            if (!processApf(str, apfFilename, i == 1, i2 == 1, i3 == 1)) {
                mApfLock.unlock();
                return null;
            }
            mApfLock.unlock();
            return apfFilename;
        } catch (InterruptedException unused) {
            return null;
        } catch (Throwable th) {
            mApfLock.unlock();
            throw th;
        }
    }

    protected boolean canUseApfResult(String str) {
        return new File(str).exists();
    }

    public static String getMimeTypeWithBitmapFactory(String str) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(str, options);
        return options.outMimeType;
    }

    public boolean processApf(String str, String str2, boolean z, boolean z2, boolean z3) {
        String str3;
        int i;
        File file = null;
        try {
            String mimeTypeWithBitmapFactory = getMimeTypeWithBitmapFactory(str);
            if (CommonDefine.IMAGE_TYPE_BMP.equals(mimeTypeWithBitmapFactory)) {
                str3 = str;
                i = 0;
            } else if ("image/png".equals(mimeTypeWithBitmapFactory)) {
                file = convertPngToBmp(str);
                if (file != null) {
                    str3 = file.toString();
                    i = 0;
                } else {
                    throw new OutOfMemoryError("in convertPngToBmp()");
                }
            } else if (!"image/jpeg".equals(mimeTypeWithBitmapFactory)) {
                return false;
            } else {
                file = convertJpegToBmp(str);
                if (file != null) {
                    i = getExifRotationValue(str);
                    str3 = file.toString();
                } else {
                    throw new OutOfMemoryError("in convertJpegToBmp()");
                }
            }
            apflib apflib = new apflib();
            apflib.interrupt();
            boolean apfFile = apflib.apfFile(str, i, str3, str2, z, z2, z3);
            Log.v("ApfAdapter", "apf returns <" + apfFile + ">");
            if (!apfFile) {
                throw new OutOfMemoryError("in apflib.apfFile()");
            } else if (!BmpFileSize.checkDiskCapacity(Environment.getExternalStorageDirectory().getPath(), 8192)) {
                throw new OutOfMemoryError("in apflib.apfFile() size check");
            } else if (file == null || !file.exists()) {
                return true;
            } else {
                file.delete();
                return true;
            }
        } catch (OutOfMemoryError e) {
            throw e;
        } catch (Exception unused) {
            if (file != null && file.exists()) {
                file.delete();
            }
            return false;
        } catch (Throwable th) {
            if (file != null && file.exists()) {
                file.delete();
            }
            throw th;
        }
    }

    protected File convertPngToBmp(String str) {
        String png2jpeg = ImageUtil.png2jpeg(mApplicationContext, str, 1);
        if (png2jpeg == null) {
            return null;
        }
        File file = new File(new File(ExternalFileUtils.getInstance(mApplicationContext).getTempViewDir()), png2jpeg);
        if (!file.exists()) {
            return null;
        }
        try {
            File file2 = new File(getTmpBmpFilename(str, FILE_PREFIX_TMP1));
            if (new EPImageUtil().jpg2bmp(file.toString(), file2.toString(), 1) != 0) {
                return null;
            }
            file.delete();
            return file2;
        } finally {
            file.delete();
        }
    }

    protected File convertJpegToBmp(String str) {
        File file;
        File file2 = null;
        try {
            file = new File(getTmpBmpFilename(str, FILE_PREFIX_TMP1));
            try {
                if (new EPImageUtil().jpg2bmp(str, file.toString(), 1) != 0) {
                    if (file.exists()) {
                        file.delete();
                    }
                    return null;
                }
                int exifRotationValue = getExifRotationValue(str);
                File file3 = new File(getTmpBmpFilename(str, FILE_PREFIX_TMP2));
                try {
                    File rotateWithExifValue = rotateWithExifValue(exifRotationValue, file, file3);
                    if (rotateWithExifValue != file && file.exists()) {
                        file.delete();
                    }
                    if (rotateWithExifValue != file3 && file3.exists()) {
                        file3.delete();
                    }
                    return rotateWithExifValue;
                } catch (Throwable th) {
                    th = th;
                    file2 = file3;
                    if (!(file == null || file == null || !file.exists())) {
                        file.delete();
                    }
                    if (!(file2 == null || file2 == null || !file2.exists())) {
                        file2.delete();
                    }
                    throw th;
                }
            } catch (Throwable th2) {
                th = th2;
                file.delete();
                file2.delete();
                throw th;
            }
        } catch (Throwable th3) {
            th = th3;
            file = null;
            file.delete();
            file2.delete();
            throw th;
        }
    }

    protected String getTmpBmpFilename(String str, String str2) {
        if (mApfImageDir == null) {
            return null;
        }
        UUID nameUUIDFromBytes = UUID.nameUUIDFromBytes(str.getBytes());
        File file = mApfImageDir;
        return new File(file, str2 + nameUUIDFromBytes.toString() + ".bmp").toString();
    }

    public String getApfFilename(String str, int i, int i2, int i3) {
        return getTmpBmpFilename(str, String.format(Locale.US, "%s%ds%dc%d_", new Object[]{FILE_PREFIX_APF, Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)}));
    }

    public static String getCurrentPrinterId(Context context) {
        String name = MyPrinter.getCurPrinter(context).getName();
        if (name == null) {
            return "";
        }
        return name.replaceFirst("(?i)^epson +", "");
    }

    public static boolean isEpsonColor(Context context, int i, int i2, boolean z) {
        return new apflib().isDspEpsonColorLogo(getCurrentPrinterId(context), i, i2, z);
    }
}
