package gen2wave.rp70biodemo.msrocr;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;
import java.lang.reflect.Method;

import elyctis.com.elytraveldocumentforandroid.PassportView;
import elyctis.com.elytraveldocumentforandroid.Scanner;
import gen2wave.rp70biodemo.R;

public class MsrOcrActivity extends Activity implements OnClickListener {

    String TAG = MsrOcrActivity.class.getSimpleName();

    private final int PROGRESS_ON = 0;
    private final int PROGRESS_OFF = 1;

    private BeepManager beepmanager = null;
    private BeepManager beepmanager_fail = null;

    private ProgressDialog mProgressDialog = null;

    private Scanner scanner = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msr_ocr);
        set_mrz_powerEnabled(true);
        String thisModel = getProperty("ro.product.model").toLowerCase();

        if (thisModel.contains("rp70a")){
            (findViewById(R.id.layout_ready)).setVisibility(View.GONE);
            (findViewById(R.id.layout_readdata)).setVisibility(View.VISIBLE);
            (findViewById(R.id.layout_readdata_ocr)).setVisibility(View.VISIBLE);
            //(findViewById(R.id.layout_idbox_ocr_data)).setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.imageView_logo)).setVisibility(View.GONE);
            ((Button) findViewById(R.id.btn_back)).setVisibility(View.GONE);

            // Make sure Scanner interface are available
            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);
        }

        Log.d(TAG, "onCreate");

        beepmanager = new BeepManager(getApplicationContext(), 1);
        beepmanager_fail = new BeepManager(getApplicationContext(), 0);

        (findViewById(R.id.layout_msr_data)).setBottom(50);
        (findViewById(R.id.layout_msr_data2)).setBottom(50);
        (findViewById(R.id.layout_msr_data3)).setBottom(50);
    }

    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();
        }
    }

    @Override
    public void onClick(View arg_view) {
        switch (arg_view.getId()) {
            case R.id.btn_back:
                (findViewById(R.id.layout_ready)).setVisibility(View.VISIBLE);
                (findViewById(R.id.layout_readdata)).setVisibility(View.GONE);
                ((Button) findViewById(R.id.btn_back)).setVisibility(View.GONE);
                break;
        }
    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String thisModel = getProperty("ro.product.model").toLowerCase();

        if (thisModel.contains("rp70a")) {
            unregisterReceiver(mMRZResultReceiver);
            scanner.finalize(1);
        }
        set_mrz_powerEnabled(false);

        if (beepmanager != null) {
            beepmanager = null;
        }
    }

    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':
                        MRZgetversion();
                        MRZread(1);
                        break;
                    case 'I':
                        updateActivity(scanner.getPassportView());
                        MRZread(2);

                        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();
                }
            }

            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");
                    }
                }
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult");
        if (requestCode == 0) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Log.d(TAG, "onRequestPermissions OK");
                scanner.resume();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {
                Log.d(TAG, "onRequestPermissions cancel");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    }

    public void Initidbox()
    {
        // Get Scanner version
        String scannerVersion = "";
        try {
            scannerVersion = Scanner.getInstance().getVersion();
            Log.d(TAG, "Scanner Version: "+scannerVersion);

            if(scannerVersion!="") {
                hideProgressIndicator();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

            Toast.makeText(getApplicationContext(), "Scanner reader not found", Toast.LENGTH_LONG).show();
        }
    }
    public void onCLickInit(View v)
    {
        // Get Scanner version
        String scannerVersion = "";
        try {
            scannerVersion = Scanner.getInstance().getVersion();
            Log.d(TAG, "Scanner Version: "+scannerVersion);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

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

    public void onCLickRead(View v)
    {
        MRZread(1);
    }

    public static String getProperty(String prop) {
        String serialnum = "";

        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class );
            serialnum = (String)(   get.invoke(c, prop, "-" )  );
        }
        catch (Exception ignored)
        {
        }
        return serialnum;
    }

    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]);
            }

            ((TextView) findViewById(R.id.tv_msrocr_type)).setText("OCR Data");
            ((TextView) findViewById(R.id.tv_ocr_data)).setText(strmrz);

            ((TextView) findViewById(R.id.tv_msrocr_name)).setText(scanner.getName());
            ((TextView) findViewById(R.id.tv_msrocr_subname)).setText(scanner.getSurname());
            ((TextView) findViewById(R.id.tv_msrocr_birthday)).setText(scanner.getBirthDate());
            ((TextView) findViewById(R.id.tv_msrocr_nationality)).setText(scanner.getNationality());
            ((TextView) findViewById(R.id.tv_msrocr_gender)).setText(scanner.getGender());
            ((TextView) findViewById(R.id.tv_msrocr_validitydata)).setText(scanner.getValidityDate());
            ((TextView) findViewById(R.id.tv_msrocr_documentnumber)).setText(scanner.getDocumentNumber());
            ((TextView) findViewById(R.id.tv_msrocr_documenttype)).setText(scanner.getDocumentType());
            ((TextView) findViewById(R.id.tv_msrocr_issuestate)).setText(scanner.getIssuingState());

            beepmanager.playBeepSoundAndVibrate(1);
        }
        else {
            Log.e(TAG, "passport.MRZ data NULL ");
            ((TextView) findViewById(R.id.tv_msrocr_type)).setText("OCR Read");
            ((TextView) findViewById(R.id.tv_ocr_data)).setText("");

            ((TextView) findViewById(R.id.tv_msrocr_name)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_subname)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_birthday)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_nationality)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_gender)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_validitydata)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_documentnumber)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_documenttype)).setText("");
            ((TextView) findViewById(R.id.tv_msrocr_issuestate)).setText("");
            beepmanager_fail.playBeepSoundAndVibrate(0);
            return;
        }
    }

    public void MRZgetversion()
    {
        String scannerVersion = "";
        try {
            scannerVersion = Scanner.getInstance().getVersion();
            ((TextView) findViewById(R.id.tv_msrocr_type)).setText("OCR Scan version");
            ((TextView)findViewById(R.id.tv_ocr_data)).setText("Scanner Version: " + scannerVersion);

        } 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();
        }
    }

    public void MRZdetect()
    {
        try {
            scanner.detectMRZ();
        }catch(IOException e){
            e.printStackTrace();
        }
    }

    private void set_mrz_powerEnabled(boolean enabled) {
        AccessoryPower.setPower(this, AccessoryPower.AccessoryType.MRZ, enabled);
    }

    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;
            }
        }
    };
}
