package com.epson.mobilephone.common.ble;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

import com.epson.mobilephone.common.maintain2.MaintainPrinter2;
import com.epson.mobilephone.common.wifidirect.WiFiDirectManager;

import java.io.IOException;

import epson.common.ExternalFileUtils;
import epson.common.Utils;
import epson.print.CommonDefine;
import epson.print.MyPrinter;
import epson.print.Util.EPLog;
import epson.print.service.EpsonService;
import epson.print.service.IEpsonService;
import epson.print.service.IEpsonServiceCallback;
import epson.scan.lib.EscanLibException;
import epson.scan.lib.ScanSettingHelper;
import epson.scan.lib.escanLib;

public class ProbePrinter {
    static final int PROBE_TIMEOUT_SEC = 180;
    private static final Object lock = new Object();
    private static escanLib mScanner = new escanLib();
    private final int BIND_SERVICE = 17;
    private final int CANCEL_FIND_PRINTER = 2;
    private final int DELAY = 100;
    private final int SEARCH_PRINTER = 1;
    private final int SELECT_PRINTER = 4;
    private BleWorkActivity.CallbackWork completion;
    private Context context;
    private volatile boolean isPrinterFound;
    private IEpsonServiceCallback mCallback = new IEpsonServiceCallback.Stub() {
        public void onGetStatusState() throws RemoteException {
            EPLog.i();
        }

        public void onGetInkState() throws RemoteException {
            EPLog.i();
        }

        public void onFindPrinterResult(String str, String str2, String str3, String str4, String str5) throws RemoteException {
            EPLog.i("find      :" + str + ":" + str2 + ":★" + str3 + "★:" + str4);
            if (str.contains("FINISH")) {
                EPLog.i(" !!  FINISH  !!");
                if (!isPrinterFound) {
                    unbindEpsonService();
                    EPLog.i(" !!  確認失敗  !!");
                    callbackCompletion(false);
                }
            } else if (str3.contains(macAddress)) {
                EPLog.i(" !!  FIND    OK    !! :" + macAddress + ": ◆");
                boolean unused = isPrinterFound = true;
                MyPrinter myPrinter = new MyPrinter(str, str2, str3, str4);
                Message obtainMessage = mHandler.obtainMessage();
                obtainMessage.obj = myPrinter;
                obtainMessage.what = 4;
                mHandler.sendMessage(obtainMessage);
                mHandler.sendEmptyMessageDelayed(2, 100);
            }
        }

        public void onNotifyProgress(int i, int i2) throws RemoteException {
            EPLog.i();
        }

        public void onNotifyContinueable(int i) throws RemoteException {
            EPLog.i();
        }

        public void onNotifyError(int i, int i2, boolean z) throws RemoteException {
            EPLog.i();
        }

        public void onNotifyEndJob(int i) throws RemoteException {
            EPLog.i();
        }
    };
    private ServiceConnection mEpsonConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            EPLog.i();
            IEpsonService unused = mEpsonService = IEpsonService.Stub.asInterface(iBinder);
            if (mEpsonService != null) {
                try {
                    mEpsonService.registerCallback(mCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        public void onServiceDisconnected(ComponentName componentName) {
            EPLog.i("ComponentName " + componentName);
            IEpsonService unused = mEpsonService = null;
        }
    };
    private IEpsonService mEpsonService;
    private Handler mHandler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message message) {
            int i = message.what;
            if (i == 4) {
                ProbePrinter probePrinter = this;
                new printerProbeTask(context, (MyPrinter) message.obj).execute(new Void[0]);
            } else if (i != 17) {
                switch (i) {
                    case 1:
                        try {
                            search();
                            break;
                        } catch (IllegalStateException e) {
                            EPLog.e(e.getMessage());
                            break;
                        }
                    case 2:
                        interruptSearch();
                        break;
                    default:
                        EPLog.i("not handled (" + message.what + ")");
                        break;
                }
            } else {
                bindEpsonService();
            }
            return false;
        }
    });
    private String macAddress;

    private ProbePrinter() {
    }

    public static ProbePrinter create() {
        return new ProbePrinter();
    }

    public ProbePrinter setContext(Context context2) {
        context = context2;
        return this;
    }

    public ProbePrinter setMacAddress(String str) {
        EPLog.d("★" + str + "★　");
        macAddress = str;
        return this;
    }

    public ProbePrinter setBleCallback(BleWorkActivity.CallbackWork callbackWork) {
        completion = callbackWork;
        return this;
    }

    public void search() throws IllegalStateException {
        String str;
        if (mEpsonService == null || completion == null || (str = macAddress) == null || str.length() != 12 || completion == null) {
            EPLog.e("Required field is not set.");
            throw new IllegalStateException("Required field is not set.");
        }
        Context context2 = context;
        context2.bindService(new Intent(context2, EpsonService.class), mEpsonConnection, 1);
        try {
            synchronized (lock) {
                isPrinterFound = false;
            }
            EPLog.d("mEpsonService.searchPrinters");
            mEpsonService.setTimeOut(180);
            mEpsonService.searchPrinters((String) null, (String) null, 1);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void interruptSearch() {
        EPLog.m68d();
        mHandler.removeMessages(1);
        if (mEpsonService != null) {
            try {
                EPLog.i("cancelSearchPrinter");
                mEpsonService.cancelSearchPrinter();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindEpsonService();
    }

    public void bindEpsonService() {
        if (mEpsonService == null) {
            Context context2 = context;
            context2.bindService(new Intent(context2, EpsonService.class), mEpsonConnection, 1);
        }
        if (mEpsonService == null) {
            EPLog.e("mEpsonService NULL");
            mHandler.sendEmptyMessageDelayed(17, 1000);
            return;
        }
        EPLog.i("bindEpsonService OK !!");
    }

    private void unbindEpsonService() {
        EPLog.i();
        if (mEpsonService != null) {
            if (!isPrinterFound) {
                mHandler.sendEmptyMessageDelayed(2, 200);
                EPLog.i("1");
            }
            try {
                EPLog.i(ExifInterface.GPS_MEASUREMENT_2D);
                EPLog.i("unregisterCallback");
                mEpsonService.unregisterCallback(mCallback);
                context.unbindService(mEpsonConnection);
                mEpsonService = null;
            } catch (RemoteException unused) {
                EPLog.e("unregisterCallback   mEpsonService");
            }
            EPLog.i(ExifInterface.GPS_MEASUREMENT_3D);
        }
    }

    private void callbackCompletion(boolean z) {
        BleWorkActivity.CallbackWork callbackWork = completion;
        if (callbackWork != null) {
            callbackWork.call(Boolean.valueOf(z));
            completion = null;
        }
    }

    private void selectPrinter(MyPrinter myPrinter) {
        myPrinter.setCurPrinter(context.getApplicationContext());
        Utils.savePref(context.getApplicationContext(), "PrintSetting", CommonDefine.RE_SEARCH, true);
        WiFiDirectManager.resetConnectInfo(context.getApplicationContext(), WiFiDirectManager.DEVICE_TYPE_PRINTER);
    }

    private class printerProbeTask extends AsyncTask<Void, Void, Integer> {
        private Context mContext;
        private MyPrinter mMyPrinter;
        private MaintainPrinter2 mPrinter = MaintainPrinter2.getInstance();

        public printerProbeTask(Context context, MyPrinter myPrinter) {
            mContext = context;
            mMyPrinter = myPrinter;
        }

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected Integer doInBackground(Void... voidArr) {
            int doProbePrinter = mPrinter.doProbePrinter(60, mMyPrinter.getPrinterId(), mMyPrinter.getIp(), 3);
            if (doProbePrinter != 0) {
                return Integer.valueOf(doProbePrinter);
            }
            mPrinter.setMSearchPos(0);
            int doSetPrinter = mPrinter.doSetPrinter();
            if (doSetPrinter != 0) {
                return Integer.valueOf(doSetPrinter);
            }
            mMyPrinter.setLang(mPrinter.doGetLang());
            ExternalFileUtils instance = ExternalFileUtils.getInstance(mContext);
            instance.createTempFolder(instance.getSupportedMediaDir());
            int epsWrapperGetSupportedMedia = mPrinter.getMEscpLib().epsWrapperGetSupportedMedia(ExternalFileUtils.getInstance(mContext).getSupportedMediaDir());
            if (epsWrapperGetSupportedMedia != 0) {
                return Integer.valueOf(epsWrapperGetSupportedMedia);
            }
            try {
                Utils.copyFile(instance.getSupportedMedia(), instance.getSavedSupportedMedia());
                EPLog.i("Success epsWrapperGetSupportedMedia");
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Utils.copyFile(instance.getAreaInfo(), instance.getSavedAreaInfo());
                EPLog.i("Success copy AreaInfo");
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            return Integer.valueOf(epsWrapperGetSupportedMedia);
        }

        protected void onPostExecute(Integer num) {
            super.onPostExecute(num);
            if (num.intValue() == 0) {
                selectPrinter(mMyPrinter);
                callbackCompletion(true);
                return;
            }
            callbackCompletion(false);
        }
    }

    private class scanProbeTask extends AsyncTask<Context, Void, Context> {
        private MyPrinter mPrinter;

        scanProbeTask(MyPrinter myPrinter) {
            mPrinter = myPrinter;
        }

        protected Context doInBackground(Context... contextArr) {
            boolean z;
            Context applicationContext = contextArr[0].getApplicationContext();
            EPLog.i("スキャナ検索処理");
            int escanWrapperInitDriver = mScanner.escanWrapperInitDriver(applicationContext);
            if (escanWrapperInitDriver == -1050) {
                z = true;
            } else if (escanWrapperInitDriver != 0) {
                EPLog.i("Scan 機能不明");
                return contextArr[0];
            } else {
                z = false;
            }
            try {
                ScanSettingHelper.recodeScannerInfo(mScanner, applicationContext, mPrinter);
                EPLog.i("Scan 機能あり");
                if (!z) {
                    mScanner.escanWrapperReleaseDriver();
                }
                EPLog.i("YYY");
                return contextArr[0];
            } catch (EscanLibException | IOException unused) {
                EPLog.i("Scan 機能なし");
                Context context = contextArr[0];
                if (!z) {
                    mScanner.escanWrapperReleaseDriver();
                }
                return context;
            } catch (Throwable th) {
                if (!z) {
                    mScanner.escanWrapperReleaseDriver();
                }
                throw th;
            }
        }

        protected void onPostExecute(Context context) {
            super.onPostExecute(context);
            EPLog.i("スキャナ検索onPostExecute");
            callbackCompletion(true);
        }
    }
}
