package epson.print.pdf;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import epson.common.ExternalFileUtils;
import epson.print.CommonDefine;
import epson.print.EPImage;
import epson.print.Util.EPLog;

public class pdfRender implements CommonDefine {
    private static final float DEF_ZOOM_PREVIEW = 0.5f;
    private static final float DEF_ZOOM_PRINT = 1.5f;
    private static final String TAG = "PDF_CONVERTER";
    private Thread backgroundThread;
    private Context mContext = null;
    private String mConvertedName;
    private String mConvertedNamePrint;
    protected volatile boolean mIsPreviewCon;
    protected boolean mOpenError = false;
    private AdobePdfContainer mPdfFile;
    private String mPdfFilename;
    protected boolean mPreviewmode = false;
    protected volatile boolean mPrintingCon;
    protected volatile boolean mRendererStart = false;
    protected boolean mRotate = false;
    protected boolean mRotateCheck = false;
    public int mTotalPage;
    private Handler mUiHandler;

    public int StartReloadDocument(String str) {
        return 0;
    }

    public void finalize() {
    }

    public pdfRender(Context context, Handler handler) {
        mContext = context;
        mUiHandler = handler;
    }

    public synchronized void startConvertPage(final int i, final int i2, final int i3) {
        if (backgroundThread == null) {
            mRendererStart = false;
            backgroundThread = new Thread(new Runnable() {
                public void run() {
                    try {
                        if  (mPdfFile != null) {
                            if (i3 == 0) {
                                mPreviewmode = true;
                                mUiHandler.sendEmptyMessage(4);
                                Log.d(pdfRender.TAG, "convert4Preview :start");
                                convert4Preview(i);
                                Log.d(pdfRender.TAG, "convert4Preview :finish");
                            } else if (i3 == 1) {
                                mPreviewmode = false;
                                Log.d(pdfRender.TAG, "printing");
                                convert4Print(i, i2);
                            }
                        }
                    } catch (Exception e) {
                        Log.e(pdfRender.TAG, "GOT ERROR WHEN CONVERT: " + e);
                    }
                    Thread unused = backgroundThread = null;
                }
            });
            backgroundThread.start();
        }
    }

    public boolean RendererStart() {
        return mRendererStart;
    }

    public boolean openPdfFile(String str, String str2, Context context) {
        boolean z;
        mRotateCheck = false;
        mPdfFile = new AdobePdfContainer(context);
        mPdfFilename = str;
        try {
            boolean parsePDF = parsePDF(str, str2);
            z = true;
            if (!parsePDF) {
                z = false;
            }
            try {
                if (mPdfFile == null || z) {
                    return z;
                }
                mTotalPage = mPdfFile.CountPages();
                mUiHandler.sendEmptyMessage(2);
                return false;
            } catch (Exception e) {
                e = e;
                Log.e(TAG, "GOT ERROR WHEN CONVERT: " + e);
                return z;
            }
        } catch (Exception e2) {
            e = e2;
            z = false;
            Log.e(TAG, "GOT ERROR WHEN CONVERT: " + e);
            return z;
        }
    }

    public boolean canPrintableDoc() {
        return mPdfFile.hasPrintPermission() == 0;
    }

    public void convert4Preview(int i) {
        ExternalFileUtils.getInstance(mContext).initPdfDir();
        mIsPreviewCon = true;
        if (convertPage(i, DEF_ZOOM_PREVIEW, 0, 1)) {
            Log.d(TAG, "convertPage Preview Finish :" + i);
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (mIsPreviewCon) {
                Bundle bundle = new Bundle();
                bundle.putInt(CommonDefine.CONVERTED_PAGE, i);
                Message message = new Message();
                message.setData(bundle);
                message.what = 0;
                mUiHandler.sendMessage(message);
                return;
            }
            Log.e(TAG, "Convert Preview NG : mIsPreviewCon = false");
            ExternalFileUtils.getInstance(mContext).initPdfDir();
        }
    }

    public void convert4Print(int i, int i2) {
        ExternalFileUtils.getInstance(mContext).initPrintDir();
        mPrintingCon = true;
        int i3 = 1;
        while (mPrintingCon) {
            if (i - 1 <= i2 - 1) {
                try {
                    if (mPrintingCon) {
                        ExternalFileUtils.getInstance(mContext).initPdfDir();
                        if (convertPage(i, DEF_ZOOM_PRINT, 1, i3)) {
                            mRendererStart = true;
                            i++;
                            i3++;
                        } else {
                            return;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            mPrintingCon = false;
            return;
        }
    }

    public boolean rotate() {
        while (!mRotateCheck) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (mOpenError) {
                break;
            }
        }
        return mRotate;
    }

    private boolean convertPage(int i, float f, int i2, int i3) {
        int i4;
        AdobePdfContainer adobePdfContainer = mPdfFile;
        if (adobePdfContainer != null) {
            try {
                float GetPageSizeX = (float) adobePdfContainer.GetPageSizeX(i);
                float GetPageSizeY = (float) mPdfFile.GetPageSizeY(i);
                EPLog.i(TAG, new File(mPdfFilename).getName() + " - " + i + CommonDefine.SLASH + mTotalPage + ": " + GetPageSizeX + "x" + GetPageSizeY);
                if (i == 1) {
                    if (GetPageSizeX > GetPageSizeY) {
                        mRotate = true;
                    } else {
                        mRotate = false;
                    }
                    mRotateCheck = true;
                    i4 = 0;
                } else if (GetPageSizeX > GetPageSizeY) {
                    i4 = !this.mRotate ? 90 : 0;
                } else {
                    i4 = !this.mRotate ? 0 : EPImage.EPS_ROTATE_270;
                }
                int i5 = (GetPageSizeX > GetPageSizeY ? 1 : (GetPageSizeX == GetPageSizeY ? 0 : -1));
                float f2 = (float) (!mPreviewmode ? 4209 : 702);
                float f3 = f2 / GetPageSizeX;
                float f4 = f2 / GetPageSizeY;
                if (f3 <= f4) {
                    f4 = f3;
                }
                float f5 = GetPageSizeX * f4;
                float f6 = f4 * GetPageSizeY;
                EPLog.i(TAG, "scaledWidth = " + f5 + ",scaledHeight = " + f6);
                System.gc();
                mConvertedName = "";
                if (i2 != 1) {
                    Bitmap pageBitmap = mPdfFile.getPageBitmap(i, (int) f5, (int) f6, i4);
                    if (pageBitmap == null) {
                        mUiHandler.sendEmptyMessage(6);
                        return false;
                    }
                    String pdfDir = ExternalFileUtils.getInstance(mContext).getPdfDir();
                    mConvertedName = new File(pdfDir, CommonDefine.UNDER_BAR + i + ".jpg").getPath();
                    saveImageToJpg(pageBitmap, mConvertedName);
                    pageBitmap.recycle();
                    Log.d(TAG, "saveImageToJpg Finish : " + mConvertedName);
                } else {
                    String pageBitmapFile = mPdfFile.getPageBitmapFile(i, (int) f5, (int) f6, i4 != 0);
                    if (pageBitmapFile == null) {
                        mUiHandler.sendEmptyMessage(6);
                        return false;
                    }
                    String decodeJpegFilename = getDecodeJpegFilename(i);
                    new File(pageBitmapFile).renameTo(new File(decodeJpegFilename));
                    Log.d(TAG, "renameTo Finish : " + decodeJpegFilename);
                }
            } catch (Exception e) {
                Log.e(TAG, "GOT ERROR WHEN CONVERT: " + e.toString());
            }
        }
        return true;
    }

    @NonNull
    public String getDecodeJpegFilename(int i) {
        String printDir = ExternalFileUtils.getInstance(mContext).getPrintDir();
        return new File(printDir, CommonDefine.UNDER_BAR + i + ".jpg").getPath();
    }

    private void saveImageToJpg(Bitmap bitmap, String str) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(str));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            fileOutputStream.write(byteArrayOutputStream.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
            Log.i(TAG, str + " converted");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean parsePDF(String str, String str2) {
        try {
            long length = new File(str).length();
            if (length == 0) {
                Log.e(TAG, "file is empty");
                mUiHandler.sendEmptyMessage(6);
                return false;
            }
            Log.i(TAG, "file: " + mPdfFilename + "has" + length + "byte");
            openFile(str, str2);
            return false;
        } catch (AdobePdfContainer.PasswordException unused) {
            Log.i(TAG, "Password Locked");
            return true;
        } catch (Throwable th) {
            th.printStackTrace();
            mUiHandler.sendEmptyMessage(6);
            mOpenError = true;
            return false;
        }
    }

    public void openFile(String str, String str2) throws AdobePdfContainer.PasswordException, AdobePdfContainer.NoPdfException {
        mPdfFile.LoadDocument(str, str2);
    }

    private byte[] readBytes(File file) throws IOException {
        int length = (int) file.length();
        byte[] bArr = new byte[length];
        FileInputStream fileInputStream = new FileInputStream(file);
        int i = 0;
        int read = fileInputStream.read(bArr, 0, length + 0);
        while (read > 0) {
            i += read;
            read = fileInputStream.read(bArr, i, length - i);
        }
        return bArr;
    }

    public boolean isFileExit() {
        return mPdfFile != null;
    }

    public int totalPages() {
        AdobePdfContainer adobePdfContainer = mPdfFile;
        if (adobePdfContainer != null) {
            return adobePdfContainer.CountPages();
        }
        return 0;
    }

    public String getConvertedPagePrint() {
        return mConvertedNamePrint;
    }

    public String getConvertedPagePreview() {
        return mConvertedName;
    }

    public void setPrintingStt(boolean z) {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mPrintingCon = z;
        if (!z) {
            while (backgroundThread != null && backgroundThread.isAlive()) {
                try {
                    Thread.sleep(2000);
                    EPLog.d("Convert Preview", "convert4Print shutdown...");
                } catch (InterruptedException | NullPointerException unused) {
                    return;
                }
            }
        }
    }

    public void setMIsPreviewCon(boolean z) {
        mIsPreviewCon = z;
    }
}
