package com.epson.iprint.shared;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import com.epson.iprint.prtlogger.CommonLog;
import com.epson.iprint.prtlogger.NewLoggerController;
import com.epson.iprint.prtlogger.PrintLog;
import com.epson.mobilephone.common.license.LicenseTopActivity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Deque;

import epson.common.Constants;
import epson.common.DialogProgress;
import epson.common.DialogProgressViewModel;
import epson.common.ExternalFileUtils;
import epson.common.IprintLicenseInfo;
import epson.common.IprintUserSurveyInfo;
import epson.common.Utils;
import epson.print.ActivityRequestPermissions;
import epson.print.ActivityViewImageSelect;
import epson.print.EPImageUtil;
import epson.print.MyPrinter;
import epson.print.R;
import epson.print.Util.EPLog;
import epson.print.WebviewActivity;
import epson.scan.activity.ScanActivity;

public class EpsoniPrintSharedActivity extends AppCompatActivity implements Runnable {
    public static final String ACTION_CONFIRM_PRINTER_SCANNER_SELECTION = "com.epson.iprint.isSetDevice";
    public static final String ACTION_PHOTO_PRINT = "com.epson.iprint.photo";
    public static final String ACTION_SCAN = "com.epson.iprint.scan";
    public static final String ACTION_WEB_PRINT = "com.epson.iprint.web";
    public static final String ACTIVITY_GET_PRINTER_INFORMATION = "epson.maintain.activity.GetPrinterReplyData";
    private static final int ACTIVITY_INTENT_PARAMETER_ERROR_ = 1;
    public static final String ACTIVITY_SCAN = "epson.scan.activity.ScanActivity";
    public static final String DIALOG_WAIT = "dialog_wait";
    public static final String GET_PRINTER_INFORMATION = "com.epson.iprint.status";
    public static final int INK_STATUS_ERROR = -1;
    public static final int INK_STATUS_INK_END = 2;
    public static final int INK_STATUS_INK_LOW = 1;
    public static final int INK_STATUS_NORMAL = 0;
    private static final int ISSETDEVICE_DEVICE_NOT_SET = 0;
    private static final int ISSETDEVICE_LOCAL_DEVICE_SET = -1;
    private static final int ISSETDEVICE_REMOTE_DEVICE_SET = -2;
    private static final String LOG_TAG = "iPrintSharedActivity";
    public static final String PACKAGE_PANASONIC_FAX = "com.panasonic.psn.fax";
    public static final String PARAM_KEY_CALLER_PACKAGE_NAME = "PACKAGE_NAME";
    private static final int REQUEST_CODE_LICENSE_CHECK = 101;
    private static final int REQUEST_PHOTO_CUSTOM = 10;
    private static final int REQUEST_RUNTIMEPERMMISSION = 100;
    private static final int REQUEST_SCAN_CUSTOM = 20;
    private static final int REQUEST_STATUS_CUSTOM = 99;
    private static final int REQUEST_WEB_CUSTOM = 30;
    public static final int RESULT_NO_SD_ERROR = 1;
    public static final int RESULT_PARAM_ERROR = 0;
    Handler mHandler = new Handler() {
        public void handleMessage(Message message) {
            if (message.what != 0) {
                EPLog.w(EpsoniPrintSharedActivity.LOG_TAG, "handleMessage::default");
                EpsoniPrintSharedActivity.this.CleanUp();
                return;
            }
            EPLog.i(EpsoniPrintSharedActivity.LOG_TAG, "handleMessage::0");
            EpsoniPrintSharedActivity.this.setWait();
        }
    };
    private DialogProgressViewModel mModelDialog;
    private Thread thread;

    protected void onCreate(Bundle bundle) {
        EPLog.i(LOG_TAG, "onCreate");
        super.onCreate(bundle);
        mModelDialog = (DialogProgressViewModel) ViewModelProviders.m2of((FragmentActivity) this).get(DialogProgressViewModel.class);
        mModelDialog.getDialogJob().observe(this, new Observer() {
            public final void onChanged(Object obj) {
                EpsoniPrintSharedActivity.lambda$onCreate$0(EpsoniPrintSharedActivity.this, (Deque) obj);
            }
        });
        NewLoggerController.stopLoggerIfNotAgreed(this);
        if (bundle == null) {
            startLicenseCheckActivity();
        } else if (!IprintLicenseInfo.isAgreedCurrentVersion(this)) {
            finish();
        } else {
            nextOnCreate();
        }
    }

    public static /* synthetic */ void lambda$onCreate$0(EpsoniPrintSharedActivity epsoniPrintSharedActivity, Deque deque) {
        String[] checkQueue = epsoniPrintSharedActivity.mModelDialog.checkQueue();
        if (checkQueue != null) {
            String str = checkQueue[0];
            String str2 = checkQueue[1];
            if (str2.equals("do_show")) {
                epsoniPrintSharedActivity.showDialog(str);
            }
            if (str2.equals("do_dismiss")) {
                epsoniPrintSharedActivity.dismissDialog(str);
            }
        }
    }

    private void startLicenseCheckActivity() {
        IprintLicenseInfo.beforeLicenseCheck(getApplicationContext());
        startActivityForResult(LicenseTopActivity.getStartIntent(getApplicationContext(), new IprintLicenseInfo(), new IprintUserSurveyInfo()), 101);
    }

    private void nextOnCreate() {
        Intent intent = getIntent();
        intent.getAction();
        if (intent.getExtras() != null) {
            try {
                InitTempFolder();
                CheckAction(intent.getAction());
                ManagePreferences managePreferences = new ManagePreferences();
                managePreferences.resetSavedFlag(getApplicationContext(), "PrintSetting");
                managePreferences.pushPreferrences(getApplicationContext());
                String action = intent.getAction();
                if (action.equals(GET_PRINTER_INFORMATION)) {
                    Intent intent2 = new Intent();
                    intent2.setClassName(getPackageName(), ACTIVITY_GET_PRINTER_INFORMATION);
                    startActivityForResult(intent2, 99);
                } else if (action.equals(ACTION_CONFIRM_PRINTER_SCANNER_SELECTION)) {
                    setPrinterScannerSelectionInfo();
                } else {
                    if (!IprintLicenseInfo.isAgreedCurrentVersion(this)) {
                        finish();
                    }
                    mHandler.sendEmptyMessage(0);
                }
            } catch (SharedDataException e) {
                e.printStackTrace();
                setResult(1);
                finish();
            } catch (IOException e2) {
                e2.printStackTrace();
                setResult(2);
                finish();
            }
        } else {
            throw new SharedDataException("bundle null error");
        }
    }

    private boolean CheckAction(String str) throws SharedDataException {
        if (str.equals(ACTION_PHOTO_PRINT) || str.equals(ACTION_SCAN) || str.equals(ACTION_WEB_PRINT) || str.equals(GET_PRINTER_INFORMATION) || str.equals(ACTION_CONFIRM_PRINTER_SCANNER_SELECTION)) {
            return true;
        }
        throw new SharedDataException("action error");
    }

    public void run() {
        EPLog.i(LOG_TAG, "run");
        try {
            Thread.sleep(100);
        } catch (InterruptedException unused) {
        }
        EPLog.i(LOG_TAG, "run::1");
        mHandler.sendEmptyMessage(1);
    }

    private void setWait() {
        mModelDialog.doShow(DIALOG_WAIT);
        thread = new Thread(new Runnable() {
            public void run() {
                EpsoniPrintSharedActivity.this.backgroundJob();
            }
        });
        try {
            if (ActivityRequestPermissions.isRuntimePermissionSupported() && getIntent().getAction().equals(ACTION_PHOTO_PRINT) && 4 == getIntent().getExtras().getInt("FILE_TYPE", 2)) {
                String[] strArr = {"android.permission.WRITE_EXTERNAL_STORAGE"};
                ActivityRequestPermissions.Permission permission = new ActivityRequestPermissions.Permission(strArr[0], new String[]{getString(R.string.permission_dialog_title), getString(R.string.permission_dialog_title)}, new String[]{ActivityRequestPermissions.DialogParameter.setMessage2((Context) this, getString(R.string.permission_dialog_message_storage)), ActivityRequestPermissions.DialogParameter.setMessage3A((Context) this, getString(R.string.permission_dialog_message_storage), getString(R.string.permission_function_storage))});
                if (!ActivityRequestPermissions.checkPermission(this, strArr)) {
                    ActivityRequestPermissions.requestPermission((Activity) this, permission, 100);
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        thread.start();
    }

    private void backgroundJob() {
        int i;
        EPLog.i(LOG_TAG, "backgroundJob");
        Intent intent = getIntent();
        if (intent == null) {
            setResult(1);
            finish();
            return;
        }
        Intent intent2 = new Intent();
        Bundle extras = intent.getExtras();
        if (extras == null) {
            setResult(1);
            finish();
            return;
        }
        try {
            if (intent.getAction().equals(ACTION_PHOTO_PRINT)) {
                SharedParamPhoto sharedParamPhoto = new SharedParamPhoto();
                sharedParamPhoto.setParam(extras);
                if (sharedParamPhoto.getPackage_name().indexOf(PACKAGE_PANASONIC_FAX) != -1) {
                    new ManagePreferences().setPreferences(PACKAGE_PANASONIC_FAX, getApplicationContext());
                } else {
                    new ManagePreferences().setPreferences(sharedParamPhoto.getMedia_type(), sharedParamPhoto.getMedia_size(), sharedParamPhoto.getColor_mode(), sharedParamPhoto.getLayout_type(), getApplicationContext());
                }
                if (sharedParamPhoto.isTIFF()) {
                    convertTiff(sharedParamPhoto);
                }
                intent2.setClass(this, ActivityViewImageSelect.class);
                intent2.setAction(intent.getAction());
                intent2.putExtra("extParam", sharedParamPhoto);
                intent2.putExtra("print_log", getPhotoPrintLog(sharedParamPhoto.getPackage_name(), 4097));
                i = 10;
            } else if (intent.getAction().equals(ACTION_SCAN)) {
                SharedParamScan sharedParamScan = new SharedParamScan();
                sharedParamScan.setParam(extras);
                if (sharedParamScan.getPixel_main() <= 0 || sharedParamScan.getPixel_sub() <= 0 || sharedParamScan.getRes_main() <= 0 || sharedParamScan.getRes_sub() <= 0) {
                    throw new SharedDataException("resolution or pixel error.");
                }
                intent2.setClass(this, ScanActivity.class);
                intent2.setAction(intent.getAction());
                intent2.putExtra("extParam", sharedParamScan);
                intent2.putExtra(ScanActivity.PARAM_KEY_SCAN_LOG, getScanLog(getCallerPackage(intent2)));
                i = 20;
            } else if (intent.getAction().equals(ACTION_WEB_PRINT)) {
                String charSequence = extras.getCharSequence("URL").toString();
                if (charSequence.length() > 0) {
                    intent2.setClass(this, WebviewActivity.class);
                    intent2.setAction(intent.getAction());
                    intent2.putExtra("android.intent.extra.TEXT", charSequence);
                    intent2.putExtra("print_log", getPhotoPrintLog(extras.getString(PARAM_KEY_CALLER_PACKAGE_NAME), PrintLog.PRINT_SOURCE_EXTERNAL_APP_WEB));
                    i = 30;
                } else {
                    throw new SharedDataException("URL error");
                }
            } else {
                setResult(1);
                finish();
                return;
            }
            startActivityForResult(intent2, i);
            mHandler.sendEmptyMessageDelayed(1, 500);
        } catch (SharedDataException e) {
            e.printStackTrace();
            setResult(1);
            finish();
        } catch (NullPointerException e2) {
            e2.printStackTrace();
            setResult(1);
            finish();
        }
    }

    private String getCallerPackage(Intent intent) {
        String stringExtra;
        if (intent == null || (stringExtra = intent.getStringExtra(PARAM_KEY_CALLER_PACKAGE_NAME)) == null) {
            return getCallingPackage();
        }
        return stringExtra;
    }

    private CommonLog getScanLog(String str) {
        CommonLog commonLog = new CommonLog();
        commonLog.action = PrintLog.ACTION_EXTERNAL_APP_SCAN;
        commonLog.callerPackage = str;
        return commonLog;
    }

    private PrintLog getPhotoPrintLog(String str, int i) {
        PrintLog printLog = new PrintLog();
        printLog.uiRoute = i;
        printLog.callerPackage = str;
        if (printLog.callerPackage == null) {
            printLog.callerPackage = getCallingPackage();
        }
        return printLog;
    }

    private int checkPrinterSelection() {
        if (getSharedPreferences("PrintSetting", 0).getString(Constants.PRINTER_NAME, "").length() <= 0) {
            return 0;
        }
        return MyPrinter.isRemotePrinter(this) ? -2 : -1;
    }

    private int checkScannerSelection() {
        String prefString = Utils.getPrefString(getApplicationContext(), Constants.SCAN_REFS_USED_SCANNER_PATH, Constants.SCAN_REFS_SCANNER_MODEL);
        return (prefString.equals(getString(R.string.str_lbl_title_scan)) || prefString.equals("")) ? 0 : -1;
    }

    private void setPrinterScannerSelectionInfo() {
        int i;
        switch (getIntent().getIntExtra("DEVICE_TYPE", -1)) {
            case 0:
                i = checkPrinterSelection();
                break;
            case 1:
                i = checkScannerSelection();
                break;
            default:
                i = 1;
                break;
        }
        setResult(i);
        finish();
    }

    private void convertTiff(SharedParamPhoto sharedParamPhoto) {
        EPImageUtil ePImageUtil = new EPImageUtil();
        ArrayList<String> arrayFileFullPath = sharedParamPhoto.getArrayFileFullPath();
        ArrayList<String> arrayFilePath = sharedParamPhoto.getArrayFilePath();
        for (int i = 0; i < arrayFilePath.size(); i++) {
            String tempSharedDir = ExternalFileUtils.getInstance(this).getTempSharedDir();
            ePImageUtil.tiff2bmp(arrayFileFullPath.get(i), new File(tempSharedDir, Utils.getPreffix(arrayFilePath.get(i)) + ".bmp").getPath());
            String tempSharedDir2 = ExternalFileUtils.getInstance(this).getTempSharedDir();
            sharedParamPhoto.setArrayFileFullPath(i, new File(tempSharedDir2, Utils.getPreffix(arrayFilePath.get(i)) + ".bmp").getPath());
        }
    }

    private void showDialog(String str) {
        DialogProgress dialogProgress;
        if (((str.hashCode() == 23812620 && str.equals(DIALOG_WAIT)) ? (char) 0 : 65535) != 0) {
            dialogProgress = null;
        } else {
            dialogProgress = DialogProgress.newInstance(str, 0, getString(R.string.str_wait));
        }
        if (dialogProgress != null) {
            dialogProgress.setCancelable(true);
            dialogProgress.show(getSupportFragmentManager(), str);
        }
    }

    private void dismissDialog(String str) {
        DialogFragment dialogFragment = (DialogFragment) getSupportFragmentManager().findFragmentByTag(str);
        if (dialogFragment != null) {
            dialogFragment.dismiss();
        }
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        EPLog.i(LOG_TAG, "onActivityResult::requestCode = " + i + "/requestCode = " + i2);
        if (i == 10) {
            setResult(i2);
        } else if (i == 20) {
            Intent intent2 = new Intent();
            if (intent != null) {
                intent2.putExtra("FILE_NAME", ScanActivity.getScanFileListFromReturnIntent(intent));
            }
            setResult(i2, intent2);
        } else if (i != 30) {
            switch (i) {
                case 99:
                    Intent intent3 = new Intent();
                    if (intent == null) {
                        setResult(i2);
                        break;
                    } else {
                        SharedParamStatus sharedParamStatus = (SharedParamStatus) intent.getSerializableExtra("extStatus");
                        if (sharedParamStatus == null) {
                            setResult(i2);
                            break;
                        } else {
                            intent3.putExtra(Constants.PRINTER_NAME, sharedParamStatus.getPrinter_name());
                            intent3.putExtra("INK_NAME", sharedParamStatus.getArrayOutInkName());
                            intent3.putExtra("INK_REMAIN", sharedParamStatus.getArrayOutInkRemain());
                            intent3.putExtra("STATUS_VALUE", sharedParamStatus.getPrinter_status());
                            intent3.putExtra("DEVICE_ID", sharedParamStatus.getPrinter_name());
                            intent3.putExtra("INK_STATUS", sharedParamStatus.getExternInkStatus());
                            setResult(i2, intent3);
                            break;
                        }
                    }
                case 100:
                    if (i2 == -1) {
                        thread.start();
                        break;
                    } else {
                        setResult(0);
                        finish();
                        break;
                    }
                case 101:
                    if (i2 != -1) {
                        finish();
                        return;
                    } else {
                        nextOnCreate();
                        return;
                    }
            }
        } else {
            setResult(i2);
        }
        finish();
    }

    protected void onDestroy() {
        super.onDestroy();
        ManagePreferences managePreferences = new ManagePreferences();
        if (managePreferences.getSavedFlag(getApplicationContext(), "PrintSetting") == 0) {
            EPLog.i(LOG_TAG, "Preference 戻す");
            managePreferences.popPreferrences(getApplicationContext());
        }
        CleanUp();
        try {
            InitTempFolder();
        } catch (IOException unused) {
        }
    }

    private void CleanUp() {
        Thread thread2 = thread;
        if (thread2 != null && thread2.isAlive()) {
            thread.interrupt();
            thread = null;
        }
        mModelDialog.doDismiss(DIALOG_WAIT);
    }

    private void InitTempFolder() throws IOException {
        ExternalFileUtils.getInstance(this).initTempSharedDir();
    }
}
