package gen2wave.rp70biodemo;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import gen2wave.rp70biodemo.fingersuprema.FingerSupremaMainActivity;
import gen2wave.rp70biodemo.iccardnfc.ICcardNFCMain;
import gen2wave.rp70biodemo.msrocr.MsrOcrActivity;
import gen2wave.rp70biodemo.passport.MRZPassportActivity;
import gen2wave.rp70biodemo.tools.Utils;

public class MainActivity extends AppCompatActivity {
    private String TAG = "Test";
    private final String SERIAL_DEBUG_TTY = "ttySAC2";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        Intent i = new Intent("com.android.server.usb.PERMISSION_DIALOG");
        i.putExtra("dialog_permission", true);
        sendBroadcast(i);
        setContentView(R.layout.activity_main);

        // check serial debug enable/disable
        String ret = Utils.exec("cat sys/class/tty/console/active");
        if (ret.equals(SERIAL_DEBUG_TTY)) {
            Toast.makeText(getApplicationContext(),
                    "Must be disable the 'Serial Debug", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // this service for destroyed using long home key(remove stack trace)
        Intent removeService = new Intent(this, RemoveTaskListenerService.class);
        startService(removeService);
        bindService(removeService, removeConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (mNfcAdapter == null) {
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        } else {
            if (!mNfcAdapter.isEnabled()) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
                alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            startActivity(new Intent("android.settings.NFC_SETTINGS"/*android.provider.Settings.ACTION_NFC_SETTINGS*/));
                        } else {
                            startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                        }
                        finish();
                    }
                });
                alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                alertDialog.setMessage("NFC was disabled.\nPlease change nfc setting");
                alertDialog.show();
            }
        }

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getPackageName(), 0);
            ((TextView) findViewById(R.id.tv_version))
                    .setText("Version" + " v"
                            + info.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (removeConnection != null) {
            unbindService(removeConnection);
        }
        Intent i = new Intent("com.android.server.usb.PERMISSION_DIALOG");
        i.putExtra("dialog_permission", false);
        sendBroadcast(i);
    }

    public void buttonClick(View v) {
        int id = v.getId();
        if (id == R.id.exit) {
            finish();
            return;
        }
        Intent intent = null;
        switch(id) {
            case R.id.btn_msrocrmenu:
                intent = new Intent(getApplicationContext(), MsrOcrActivity.class);
                break;
            case R.id.btn_passmenu:
                intent = new Intent(getApplicationContext(), MRZPassportActivity.class);
                break;
            case R.id.btn_fingermenu_morpho:
                intent = new Intent(getApplicationContext(), FingerSupremaMainActivity.class);
                break;
            case R.id.btn_iccard_nfc:
                intent = new Intent(getApplicationContext(), ICcardNFCMain.class);
                break;
        }
        startActivity(intent);
    }

    // service connection
    private ServiceConnection removeConnection = new ServiceConnection() {
    // Called when the connection with the service is established
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d(TAG, "removeConnection connected");
            RemoveTaskListenerService.RemoveBinder binder = (RemoveTaskListenerService.RemoveBinder) service;
            // register callback
            binder.getService().registerCallback(removeCallback);
        }

        // Called when the connection with the service disconnects unexpectedly
        public void onServiceDisconnected(ComponentName className) {
            Log.d(TAG, "removeConnection disconnected");
        }
    };

    private RemoveTaskListenerService.IRemoveCallback removeCallback =
            new RemoveTaskListenerService.IRemoveCallback() {
        @Override
        public void recvRemoveEvent() {
            Log.d(TAG, "recvRemoveEvent called");
            finish();
        }
    };
}
