package epson.print.screen;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epson.iprint.prtlogger.Analytics;
import com.epson.mobilephone.common.escpr.MediaInfo;
import com.epson.mobilephone.common.wifidirect.escprLib;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;

import epson.common.Constants;
import epson.common.IPAddressUtils;
import epson.common.Utils;
import epson.common.httpclient.IAHttpClient;
import epson.print.ActivityIACommon;
import epson.print.CommonDefine;
import epson.print.MyPrinter;
import epson.print.R;
import epson.print.Util.EPLog;
import epson.print.service.EpsonService;
import epson.print.service.IEpsonService;
import epson.print.service.IEpsonServiceCallback;
import epson.print.widgets.AbstractListBuilder;
import epson.print.widgets.CustomTitleAlertDialogBuilder;
import epson.print.widgets.PrinterInfoBuilder;

public class PrinterFinder extends ActivityIACommon {
    private static final int DELAY = 100;
    private static final int DIALOG_INFORM = 0;
    private static boolean foundPrinter = false;
    private static final Object mLock = new Object();
    private final int CANCEL_FIND_PRINTER = 2;
    private final int DISPLAY_FIND_RESULT = 6;
    private final int INFORM_DIALOG = 5;
    private final String PRINTER_COMMON_DEVICENAME = "common_devicename";
    private final String PRINTER_ID = "id";
    private final String PRINTER_INDEX = "index";
    private final String PRINTER_IP = escprLib.PRINTER_IP;
    private final String PRINTER_NAME = "name";
    private final int SEARCH_PRINTER = 1;
    private final int SELECT_PRINTER = 4;
    private final int UPDATE_PRINTER = 3;
    int curError;
    private boolean isDialogOpen = false;
    private boolean isFinishSearchPrinter = false;
    private Boolean isFocused = true;
    AbstractListBuilder mBuilder;
    private IEpsonServiceCallback mCallback = new IEpsonServiceCallback.Stub() {
        public void onGetInkState() throws RemoteException {
        }

        public void onGetStatusState() throws RemoteException {
        }

        public void onNotifyContinueable(int i) throws RemoteException {
        }

        public void onNotifyEndJob(int i) throws RemoteException {
        }

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

        public void onFindPrinterResult(String str, String str2, String str3, String str4, String str5) throws RemoteException {
            Message obtain = Message.obtain();
            obtain.what = 3;
            Bundle bundle = new Bundle();
            bundle.putString("name", str);
            bundle.putString(escprLib.PRINTER_IP, str2);
            bundle.putString("id", str3);
            bundle.putString("common_devicename", str5);
            obtain.setData(bundle);
            PrinterFinder.this.mHandler.sendMessage(obtain);
        }

        public void onNotifyError(int i, int i2, boolean z) throws RemoteException {
            synchronized (PrinterFinder.mLock) {
                boolean unused = PrinterFinder.foundPrinter = Utils.getPrefBoolean(PrinterFinder.this.getApplicationContext(), "PrintSetting", CommonDefine.RE_SEARCH);
                if ((i2 == -1300 || i2 == -1351) && !PrinterFinder.foundPrinter) {
                    i2 = -1100;
                } else if ((i2 == -1300 || i2 == -1351 || i2 == -1100) && PrinterFinder.foundPrinter) {
                    i2 = -11001;
                }
            }
            PrinterFinder printerFinder = PrinterFinder.this;
            printerFinder.curError = i2;
            printerFinder.mHandler.sendEmptyMessage(5);
        }
    };
    Context mContext;
    private ServiceConnection mEpsonConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName componentName) {
            try {
                PrinterFinder.this.mEpsonService.unregisterCallback(PrinterFinder.this.mCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            IEpsonService unused = PrinterFinder.this.mEpsonService = null;
        }

        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            IEpsonService unused = PrinterFinder.this.mEpsonService = IEpsonService.Stub.asInterface(iBinder);
            if (PrinterFinder.this.mEpsonService != null) {
                try {
                    PrinterFinder.this.mEpsonService.registerCallback(PrinterFinder.this.mCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private IEpsonService mEpsonService = null;
    Handler mHandler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case 1:
                    if (PrinterFinder.this.mEpsonService == null) {
                        PrinterFinder.this.mHandler.sendEmptyMessageDelayed(1, 100);
                        break;
                    } else {
                        try {
                            boolean unused = PrinterFinder.this.isFinishSearchPrinter = false;
                            PrinterFinder.this.searchButtonSetEnabled(false);
                            PrinterFinder.this.mProgressBar.setVisibility(0);
                            ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(PrinterFinder.this.getString(R.string.searching_text));
                            PrinterFinder.this.mEpsonService.searchPrinters((String) null, (String) null, 1);
                            break;
                        } catch (RemoteException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                case 2:
                    if (PrinterFinder.this.mEpsonService != null) {
                        try {
                            PrinterFinder.this.mEpsonService.cancelSearchPrinter();
                            break;
                        } catch (RemoteException e2) {
                            e2.printStackTrace();
                            break;
                        }
                    }
                    break;
                case 3:
                    final Bundle data = message.getData();
                    String string = data.getString("name");
                    if (string == null || string.contentEquals("FINISH")) {
                        if (!PrinterFinder.this.mIsClickSelect) {
                            if (PrinterFinder.this.mBuilder.getData().size() <= 0) {
                                ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(PrinterFinder.this.getString(R.string.EPS_PRNERR_COMM_TITLE1));
                            } else if (Locale.getDefault().getLanguage().equalsIgnoreCase(Locale.JAPAN.getLanguage()) || Locale.getDefault().getLanguage().equalsIgnoreCase(Locale.JAPANESE.getLanguage())) {
                                ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(PrinterFinder.this.getString(R.string.numberOfPrintersAvailable));
                                ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(PrinterFinder.this.getString(R.string.numberOfPrintersAvailable));
                            } else {
                                ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(String.format(PrinterFinder.this.getString(R.string.numberOfPrintersAvailable), new Object[]{Integer.valueOf(PrinterFinder.this.mBuilder.getData().size())}));
                            }
                            PrinterFinder.this.mBuilder.getAdapter().notifyDataSetChanged();
                            PrinterFinder.this.mProgressBar.setVisibility(8);
                            PrinterFinder.this.searchButtonSetEnabled(true);
                            boolean unused2 = PrinterFinder.this.isFinishSearchPrinter = true;
                            break;
                        }
                    } else {
                        synchronized (PrinterFinder.mLock) {
                            if (!PrinterFinder.this.printerList.contains(data.getString("id"))) {
                                new AsyncTask<Void, Void, MyPrinter[]>() {
                                    protected MyPrinter[] doInBackground(Void... voidArr) {
                                        IAHttpClient.HttpResponse httpResponse;
                                        String buildURL = IPAddressUtils.buildURL(Analytics.EXTENSION_STRING_WEB, data.getString(escprLib.PRINTER_IP), "/PRESENTATION/EPSONCONNECT");
                                        IAHttpClient.HttpGet httpGet = new IAHttpClient.HttpGet(buildURL);
                                        IAHttpClient iAHttpClient = new IAHttpClient();
                                        iAHttpClient.setFollowRedirects(false);
                                        try {
                                            httpResponse = iAHttpClient.execute(httpGet);
                                        } catch (IOException unused) {
                                            EPLog.d("httpResponse", "IOException");
                                            httpResponse = null;
                                        }
                                        if (httpResponse != null) {
                                            int responseCode = httpResponse.getResponseCode();
                                            EPLog.d("Response", "res : " + responseCode);
                                            if (200 == responseCode || (300 <= responseCode && responseCode < 400)) {
                                                MyPrinter myPrinter = new MyPrinter(data.getString("name"), data.getString(escprLib.PRINTER_IP), data.getString("id"), (String) null);
                                                myPrinter.setCommonDeviceName(data.getString("common_devicename"));
                                                return new MyPrinter[]{myPrinter};
                                            } else if (404 == responseCode) {
                                                EPLog.d("Response", "NotFound:" + buildURL);
                                            } else {
                                                EPLog.d("Response", "Error:" + buildURL);
                                            }
                                        }
                                        return null;
                                    }

                                    protected void onPostExecute(MyPrinter[] myPrinterArr) {
                                        super.onPostExecute(myPrinterArr);
                                        if (myPrinterArr != null) {
                                            ((PrinterInfoBuilder) PrinterFinder.this.mBuilder).addPrinter(myPrinterArr[0]);
                                            PrinterFinder.this.printerList.add(data.getString("id"));
                                        }
                                    }
                                }.execute(new Void[0]);
                                boolean unused3 = PrinterFinder.foundPrinter = true;
                                break;
                            } else {
                                break;
                            }
                        }
                    }
                    break;
                case 4:
                    if (PrinterFinder.this.mEpsonService != null) {
                        try {
                            PrinterFinder.this.mEpsonService.setCurPrinter(message.getData().getInt("index"));
                        } catch (RemoteException e3) {
                            e3.printStackTrace();
                        }
                    }
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.PRINTER_NAME, message.getData().getString("name"));
                    bundle.putString(Constants.PRINTER_IP, message.getData().getString(escprLib.PRINTER_IP));
                    bundle.putString(Constants.PRINTER_ID, message.getData().getString("id"));
                    intent.putExtras(bundle);
                    PrinterFinder.this.setResult(-1, intent);
                    PrinterFinder.this.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(IPAddressUtils.buildURL(Analytics.EXTENSION_STRING_WEB, message.getData().getString(escprLib.PRINTER_IP), "/PRESENTATION/EPSONCONNECT"))));
                    PrinterFinder.this.finish();
                    break;
                case 5:
                    if (!PrinterFinder.this.isDialogOpen) {
                        boolean unused4 = PrinterFinder.this.isDialogOpen = true;
                        EPLog.i("mHandler", "curError = " + PrinterFinder.this.curError);
                        PrinterFinder.this.showDialog(0);
                        break;
                    }
                    break;
            }
            return false;
        }
    });
    boolean mIsClickSelect = false;
    ViewGroup mLayout;
    ProgressBar mProgressBar;
    Button mSearchButton;
    private ArrayList<String> printerList = new ArrayList<>();

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        if (this.mEpsonService == null) {
            bindService(new Intent(this, EpsonService.class), mEpsonConnection, 1);
        }
        printerList.clear();
        mLayout = (ViewGroup) getLayoutInflater().inflate(R.layout.search_printer_layout, (ViewGroup) null);
        buildElements();
        mIsClickSelect = false;
        setContentView((View) mLayout);
        mContext = this;
        setActionBar((int) R.string.remoteprinter_get_emailadress, true);
    }

    private void buildElements() {
        mLayout.findViewById(R.id.rl_localremoteselect).setVisibility(8);
        mSearchButton = (Button) mLayout.findViewById(R.id.function_button);
        mProgressBar = (ProgressBar) mLayout.findViewById(R.id.progress_bar);
        searchButtonSetEnabled(false);
        mProgressBar.setVisibility(0);
        mLayout.findViewById(R.id.ble_wifi_setting).setVisibility(8);
        mLayout.findViewById(R.id.not_found_printer_epsonsn).setVisibility(8);
        mBuilder = new PrinterInfoBuilder(getBaseContext(), mLayout, 0);
        mBuilder.setResource(getIntent().getExtras().getString(Constants.PRINTER_NAME));
        mBuilder.build();
        mBuilder.refresh();
        ((ListView) mLayout.findViewById(16908298)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                if (PrinterFinder.this.isFocused.booleanValue()) {
                    Boolean unused = PrinterFinder.this.isFocused = false;
                    PrinterFinder printerFinder = PrinterFinder.this;
                    printerFinder.mIsClickSelect = true;
                    Message obtainMessage = printerFinder.mHandler.obtainMessage();
                    obtainMessage.what = 4;
                    Bundle bundle = new Bundle();
                    bundle.putInt("index", i);
                    bundle.putString("name", ((MyPrinter) PrinterFinder.this.mBuilder.getData().elementAt(i)).getName());
                    bundle.putString("id", ((MyPrinter) PrinterFinder.this.mBuilder.getData().elementAt(i)).getPrinterId());
                    bundle.putString(escprLib.PRINTER_IP, ((MyPrinter) PrinterFinder.this.mBuilder.getData().elementAt(i)).getIp());
                    obtainMessage.setData(bundle);
                    PrinterFinder.this.mHandler.sendMessageDelayed(obtainMessage, 100);
                }
            }
        });
        mSearchButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                synchronized (PrinterFinder.mLock) {
                    PrinterFinder.this.printerList.clear();
                    PrinterFinder.this.mBuilder.refresh();
                }
                boolean unused = PrinterFinder.this.isFinishSearchPrinter = false;
                PrinterFinder.this.searchButtonSetEnabled(false);
                PrinterFinder.this.mProgressBar.setVisibility(0);
                ((TextView) PrinterFinder.this.mLayout.findViewById(R.id.empty)).setText(PrinterFinder.this.getString(R.string.searching_text));
                PrinterFinder.this.mHandler.sendEmptyMessageDelayed(1, 100);
            }
        });
    }

    protected void onDestroy() {
        super.onDestroy();
        if (this.mEpsonService != null) {
            if (!this.isFinishSearchPrinter) {
                mHandler.sendEmptyMessageDelayed(2, 200);
            }
            try {
                mEpsonService.unregisterCallback(this.mCallback);
                unbindService(this.mEpsonConnection);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        mBuilder.destructor();
    }

    public void onBackPressed() {
        super.onBackPressed();
        try {
            mEpsonService.cancelSearchPrinter();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    protected void onResume() {
        super.onResume();
        EPLog.e("Epson", "PrinterFinder.java call onResume()");
        mHandler.sendEmptyMessageDelayed(1, 100);
        EPLog.d("PrinterFinder", "Send CHECK_PRINTER Message.");
    }

    protected void onPause() {
        EPLog.d("SearchPrinterScr", "onPause");
        super.onPause();
    }

    protected Dialog onCreateDialog(int i) {
        if (i != 0) {
            return null;
        }
        EPLog.i("DIALOG_INFORM", "curError = " + curError);
        int i2 = curError;
        if (!(i2 == -1100 && i2 == -11001)) {
            if (Utils.getPrefBoolean(getApplicationContext(), "PrintSetting", CommonDefine.RE_SEARCH)) {
                curError = -11001;
            } else {
                curError = -1100;
            }
        }
        Integer[] stringId = MediaInfo.ErrorTable.getStringId(this.curError);
        if (stringId == null) {
            stringId = new Integer[]{Integer.valueOf(R.string.NOT_IMPLEMENT), Integer.valueOf(R.string.NOT_IMPLEMENT_TITLE)};
        }
        String string = getString(stringId[0].intValue());
        String ssid = Utils.getSSID(this);
        if (Utils.isConnectedWifi(this) && curError == -11001 && ssid != null) {
            string = String.format(getString(R.string.EPS_ERR_PRINTER_NOT_FOUND_RESEARCH), new Object[]{ssid});
        }
        return new CustomTitleAlertDialogBuilder(this).setCancelable(false).setTitle(getString(stringId[1].intValue())).setMessage(string).setNegativeButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                PrinterFinder.this.removeDialog(0);
                boolean unused = PrinterFinder.this.isDialogOpen = false;
            }
        }).create();
    }

    public void searchButtonSetEnabled(boolean z) {
        mSearchButton.setVisibility(0);
        if (z) {
            mSearchButton.setEnabled(true);
        } else {
            mSearchButton.setEnabled(false);
        }
    }
}
