package gen2wave.g2w_rp70a_mrz_demo;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.amarula.gen2wave.sdk.usbaccessory.AccessoryPower;

import java.io.IOException;

import elytraveldocumentforandroid.PassportView;
import elytraveldocumentforandroid.Scanner;

public class MainActivity extends AppCompatActivity {

    String TAG = getClass().getSimpleName();

    private final int PROGRESS_ON = 0;
    private final int PROGRESS_OFF = 1;
    private ProgressDialog mProgressDialog = null;

    private Scanner scanner = null;
    private BeepManager beepmanager = null;
    private TextView mrzValueTxt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        set_mrz_powerEnabled(true);

        mrzValueTxt=(TextView) findViewById(R.id.mrz_value_txt_search);
        IntentFilter mrzfilter = new IntentFilter();
        mrzfilter.addAction(Scanner.EXTRA_MRZ_DATA_ACTION);
        mrzfilter.addAction(Scanner.EXTRA_MRZ_INIT_ACTION);
        mrzfilter.addAction(Scanner.ACTION_USB_PERMISSION);
        registerReceiver(mMRZResultReceiver, mrzfilter);
        beepmanager = new BeepManager(getApplicationContext(), 1);
    }

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

        if (scanner != null)
            scanner.finalize(1);
        mHandler.sendEmptyMessageDelayed(PROGRESS_ON, 100);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mMRZResultReceiver);
        scanner.finalize(1);
        if(beepmanager!=null){
            beepmanager=null;
        }
        set_mrz_powerEnabled(false);
    }

    private void showProgressDialog() {
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMessage("Initialize...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    private void hideProgressIndicator() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    private BroadcastReceiver mMRZResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context ctx, Intent intent) {
            /* Do not double read while scanning with activity */
            String action = intent.getAction();
            Log.v(TAG, "onReceive() action = "+action);

            if (action.equals(Scanner.EXTRA_MRZ_DATA_ACTION)) {
                byte datatype = intent.getByteExtra(Scanner.EXTRA_MRZ_DATA_TYPE,(byte)0x00);

                switch (datatype){
                    case 'V':
                        //   hideProgressIndicator();
                        try {
                            Thread.sleep(1000);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        MRZgetversion();
                        MRZread(1);
                        break;
                    case 'I':
                        updateActivity(scanner.getPassportView());
                        MRZread(2);
                        //MRZdetect();
                        break;
                    case 'P':
                        byte datastate = intent.getByteExtra(Scanner.EXTRA_MRZ_DETECT_EMPTY, (byte) 0x10);
                        Log.v(TAG, "onReceive() datatype:"+String.format("%02X ", datatype)+" datastate:"+String.format("%02X ", datastate));
                        break;
                    case 'E':
                        MRZgetversion();
                        MRZread(1);
                        break;
                }
            }

            if(action.equals(Scanner.EXTRA_MRZ_INIT_ACTION)){
                boolean bhaspermission = intent.getBooleanExtra(Scanner.EXTRA_MRZ_INIT_PERMISSION,false);
                if(bhaspermission) {
                    MRZgetversion();
                    //MRZread(1);
                }
                else {
                    // scanner.resume();
                }
            }

            if(action.equals(Scanner.ACTION_USB_PERMISSION)){
                synchronized (this){
                    if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,false)){
                        Log.d(TAG, "RequestPermissionsResult   true");
                        scanner.resume();
                    }
                    else{
                        Log.d(TAG, "RequestPermissionsResult   false");
                    }
                }
            }
        }
    };

    public void MRZgetversion()
    {
        String scannerVersion = "";
        try {
            scannerVersion = Scanner.getInstance().getVersion();


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            Toast.makeText(getApplicationContext(), "Scanner reader not found", Toast.LENGTH_LONG).show();
        }
    }

    public void MRZread(int readtype)
    {

        try {
            if(readtype ==1) {
                scanner.readMRZ();
            }
            else if(readtype ==2||readtype ==3) {
                scanner.creadMRZ(readtype);
            }
            else {
                scanner.readMRZ();
            }
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void updateActivity(PassportView passport)
    {
        String strmrz="";

        //Update MRZ UI
        if(passport!=null) {
            if(passport.is1lines) {
                strmrz += passport.MRZ[0] +"\n";
                Log.d("MRZ", passport.MRZ[0]);
            }
            if(passport.is2lines){
                strmrz+=passport.MRZ[1]+"\n";
                Log.d("MRZ", passport.MRZ[1]);
            }
            if (passport.is3lines) {
                strmrz+=passport.MRZ[2];
                Log.d("MRZ", passport.MRZ[2]);
            }

            mrzValueTxt.setText(strmrz);

            beepmanager.playBeepSoundAndVibrate(1);
        }
        else {
            Log.e(TAG, "passport.MRZ data NULL ");

            beepmanager.playBeepSoundAndVibrate(0);
            return;
        }
    }

    private void set_mrz_powerEnabled(boolean enabled) {
        AccessoryPower.setPower(this, AccessoryPower.AccessoryType.MRZ, enabled);
        Log.d(TAG, "Power Get=" + AccessoryPower.powerEnabled(AccessoryPower.AccessoryType.MRZ));
    }

    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PROGRESS_ON:
                {
                    showProgressDialog();
                    mHandler.sendEmptyMessageDelayed(PROGRESS_OFF, 4000);
                    break;
                }
                case PROGRESS_OFF:
                {
                    try {
                        scanner = Scanner.getInstance(getApplicationContext());
                        Thread.sleep(100);
                        scanner.resume();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    hideProgressIndicator();
                    break;
                }
                default:
                    break;
            }
        }
    };
}
