package gen2wave.rp70biodemo.fingersuprema;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amarula.gen2wave.sdk.usbaccessory.AccessoryPower;
import com.suprema.BioMiniFactory;
import com.suprema.CaptureResponder;
import com.suprema.IBioMiniDevice;
import com.suprema.IUsbEventHandler;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import gen2wave.rp70biodemo.R;
import gen2wave.rp70biodemo.tools.MainTabPagerAdapter;
import gen2wave.rp70biodemo.tools.SendCommToDatabaseFragment;
import gen2wave.rp70biodemo.tools.SendCommToEnrollFragment;
import gen2wave.rp70biodemo.tools.SendDataToSearchFragment;


public class FingerSupremaMainActivity extends AppCompatActivity {

    private UsbManager mUsbManager = null;
    private PendingIntent mPermissionIntent= null;
    private static BioMiniFactory mBioMiniFactory = null;
    public static final int REQUEST_WRITE_PERMISSION = 786;
    public IBioMiniDevice mCurrentDevice = null;
    private final String USB_ACTION = "com.gen2wave.suprema.USB_ACTION";

    public static final boolean mbUsbExternalUSBManager = false;
    private static final String ACTION_USB_PERMISSION = "com.android.suprema.USB_PERMISSION";


    private FingerSupremaMainActivity mainContext;
    String TAG = getClass().getSimpleName();

    TabLayout tabLayout = null;
    ViewPager viewPager = null;
    MainTabPagerAdapter mTabPagerAdapter = null;

    private final int ALERT_ENROLL_MESSAGE = 900;
    private final int SEND_DATA_TO_SEARCH_FRAGMENT = 901;
    private final int SET_TEXT_PROCESS_BTN = 902;
    private final int UPDATE_SENSOR_MESSAGE = 903;
    private final int UPDATE_IMAGE = 904;
    private final int UPDATE_SENSOR_PROGRESS = 905;

    private int currentPage = 0;
    private final int SEARCHPAGE = 0;
    private final int ENROLLPAGE = 1;
    private final int DATABASEPAGE = 2;

    Button processStartBtn = null;

    SendDataToSearchFragment dataPasserToSearch;
    SendCommToDatabaseFragment sendCommToDatabaseFragment;
    SendCommToEnrollFragment sendCommToEnrollFragment;



    private ListView databaseListView = null;
   /* private ArrayList<String> mUsersname;;
    private ArrayAdapter itemsAdapter;
    private ListView listviewdata;
*/
   DbHelper dbhelper;
    SQLiteDatabase db;
    Cursor cursor;

    boolean isDestroy = false, isDetach = false, isInitPower = false;

    class UserData {
        String userid;
        ///String first_name;
        //String last_name;
        byte[] template;
        public UserData(String uid, byte[] data, int len) {//String fname,String lname, byte[] data, int len) {
            //this.first_name = fname;
            this.userid= uid;
            //this.last_name = lname;
            this.template = Arrays.copyOf(data, len);
        }
    }
    private ArrayList<UserData> mUsers = new ArrayList<>();
    /*private ArrayList<String> mUsersname = new ArrayList<String>();
    private ArrayAdapter itemsAdapter;
    private ListView listviewdata;*/

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

        // this service for destroyed using long home key(remove stack trace)

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        set_fp_powerEnabled(true);

        setContentView(R.layout.activity_finger_suprema_main);

        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Search"));
        tabLayout.addTab(tabLayout.newTab().setText("Enroll"));
        tabLayout.addTab(tabLayout.newTab().setText("Database"));

        tabLayout.setOnTabSelectedListener(onTabSelectedListener);

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));



        List<Fragment> list = new ArrayList<>();
        list.add(new SpSearchFragment());
        list.add(new SpEnrollFragment());
        list.add(new SpDatabaseFragment());



        mTabPagerAdapter = new MainTabPagerAdapter(getSupportFragmentManager(), list);
        viewPager.setAdapter(mTabPagerAdapter);

        processStartBtn = (Button) findViewById(R.id.process_start_btn);
        processStartBtn.setOnClickListener(btnClickListener);
        mainContext = this;

        dbhelper = new DbHelper(this);
        db = dbhelper.getWritableDatabase();



        cursor = db.rawQuery("select * from tablename",null);

        while(cursor.moveToNext()){
            mUsers.add(new UserData(cursor.getString(0),cursor.getBlob(1),cursor.getBlob(1).length));
        }
        restartBioMini();
/*
        mUsersname = new ArrayList<String>();
        Log.d(TAG, "ArrayAdapter");
        itemsAdapter= new ArrayAdapter(this,android.R.layout.simple_list_item_1,mUsersname);
        Log.d(TAG, "listviewdata");
*/

    }

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

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        isDestroy = true;
        if (mBioMiniFactory != null) {
            mBioMiniFactory.close();
            mBioMiniFactory = null;
        }

        Log.d(TAG, "onDestroy  - closeDeviceAndFinishActivity");
        closeDeviceAndFinishActivity();
        set_fp_powerEnabled(false);
    }

    private void powerOnOff(int onoff) {
        Log.d(TAG, "onoff = "+onoff);

    }

    Button.OnClickListener btnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.process_start_btn:
                    onStartStop();
                    break;
            }
        }
    };





    private final BroadcastReceiver actionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[FingerMainActivity] action = "+action);
            if (action.equals(Intent.ACTION_SCREEN_OFF)) {
                //if (ProcessInfo.getInstance().isStarted()) {
                    notifyEndProcess();
               // }
            } else if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
                Log.d(TAG, "ACTION_USB_DEVICE_ATTACHED");
                UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                Log.d(TAG, "getVendorId = "+device.getVendorId()+", getProductId = "+device.getProductId());
//                int count = countDevices();
//                if (count > 0) {
//                    onStartStop();
//                }
                int checkPermission = ContextCompat.checkSelfPermission(getApplicationContext(), USB_ACTION);


            } else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
                isDetach = true;
                finish();
            }
        }
    };



    private void notifyEndProcess() {
        Log.d(TAG, "notifyEndProcess");
        Message msg = new Message();
        msg.what = SET_TEXT_PROCESS_BTN;
        msg.obj = "Start Button";
        if(mCurrentDevice.isCapturing()==true) {
            Log.d(TAG, "abortCapturing");
            mCurrentDevice.abortCapturing();
        }

        ((EditText) findViewById(R.id.user_id)).setText("");
        ((TextView)findViewById(R.id.textViewMessage_enroll)).setText("Sensor Message...");
        ((ImageView) findViewById(R.id.imageView_enroll)).setImageBitmap(null);
    }

    TabLayout.OnTabSelectedListener onTabSelectedListener = new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            int pos = tab.getPosition();
            Log.d(TAG, "onTabSelected post = " + pos);
            viewPager.setCurrentItem(pos);

            if (pos == SEARCHPAGE && currentPage != pos) {
                Log.d(TAG, "SEARCHPAGE ");
                mUsers.clear();
                cursor = db.rawQuery("select * from tablename",null);

                while(cursor.moveToNext()){
                    mUsers.add(new UserData(cursor.getString(0),cursor.getBlob(1),cursor.getBlob(1).length));
                }
                currentPage = pos;
                onStartStop();
            } else if (pos == ENROLLPAGE){
                currentPage = pos;
                if(mCurrentDevice!=null){
                    notifyEndProcess();
                }
            }else if(pos ==DATABASEPAGE){
                currentPage = pos;
                if(mCurrentDevice!=null) {
                    if (mCurrentDevice.isCapturing() == true) {
                        Log.d(TAG, "abortCapturing");
                        mCurrentDevice.abortCapturing();
                    }
                }
            }
            if (pos == DATABASEPAGE) processStartBtn.setVisibility(View.GONE);
            else processStartBtn.setVisibility(View.VISIBLE);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            //background thread puase
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            //refresh
        }
    };


    private IBioMiniDevice.CaptureOption mCaptureOptionDefault = new IBioMiniDevice.CaptureOption();
    private CaptureResponder mCaptureResponseDefault = new CaptureResponder() {
        @Override
        public boolean onCaptureEx(final Object context, final Bitmap capturedImage,
                                   final IBioMiniDevice.TemplateData capturedTemplate,
                                   final IBioMiniDevice.FingerState fingerState) {
            Log.d(TAG,"onCapture : Capture successful!");
            Log.d(TAG,getResources().getText(R.string.capture_single_ok).toString());

            Log.d(TAG,((IBioMiniDevice) context).popPerformanceLog());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(capturedImage != null) {
                        ImageView iv = (ImageView) findViewById(R.id.imageView1);
                        if(iv != null) {
                            iv.setImageBitmap(capturedImage);
                        }
                    }
                }
            });
            return true;
        }

        @Override
        public void onCaptureError(Object contest, int errorCode, String error) {
            Log.d(TAG,"onCaptureError : " + error + " ErrorCode :" + errorCode);
            if( errorCode != IBioMiniDevice.ErrorCode.OK.value())
                Log.d(TAG,getResources().getText(R.string.capture_single_fail) + "("+error+")");
        }
    };

    private CaptureResponder mCaptureResponsePrev = new CaptureResponder() {
        @Override
        public boolean onCaptureEx(final Object context, final Bitmap capturedImage,
                                   final IBioMiniDevice.TemplateData capturedTemplate,
                                   final IBioMiniDevice.FingerState fingerState) {

            Log.d("CaptureResponsePrev", String.format(Locale.ENGLISH , "captureTemplate.size (%d) , fingerState(%s)" , capturedTemplate== null? 0 : capturedTemplate.data.length, String.valueOf(fingerState.isFingerExist)));
            Log.d(TAG,getResources().getText(R.string.start_capture_ok).toString());
            byte[] pImage_raw =null;
            if( (mCurrentDevice!= null && (pImage_raw = mCurrentDevice.getCaptureImageAsRAW_8() )!= null)) {
                Log.d("CaptureResponsePrev ", String.format(Locale.ENGLISH, "pImage (%d) , FP Quality(%d)", pImage_raw.length , mCurrentDevice.getFPQuality(pImage_raw, mCurrentDevice.getImageWidth(), mCurrentDevice.getImageHeight(), 2)));
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if(capturedImage != null) {
                        ImageView iv = (ImageView) findViewById(R.id.imageView1);
                        if(iv != null) {
                            iv.setImageBitmap(capturedImage);
                        }
                    }
                }
            });
            return true;
        }

        @Override
        public void onCaptureError(Object context, int errorCode, String error) {
            Log.d(TAG,"onCaptureError : " + error);
            Log.d(TAG,((IBioMiniDevice)context).popPerformanceLog());
            if( errorCode != IBioMiniDevice.ErrorCode.OK.value())
                Log.d(TAG,getResources().getText(R.string.start_capture_fail).toString());
        }
    };

    public void onStartStop() {
        Log.d(TAG, "onStartStop called");
        if (currentPage == SEARCHPAGE) {

            if (mCurrentDevice != null) {
                if (mUsers.size() == 0) {
                    Log.d(TAG,"There is no enrolled data");
                    ((TextView)findViewById(R.id.textViewMessage)).setText("There is no enrolled data");
                    return;
                }
                Log.d(TAG,"capture fingerprint image");
                // capture fingerprint image
                IBioMiniDevice.CaptureOption option = new IBioMiniDevice.CaptureOption();
                option.extractParam.captureTemplate = true;
                option.captureTemplate = true; //deprecated
                Log.d(TAG,"getDeviceClass");
                if (mCurrentDevice.getDeviceInfo().scannerType.getDeviceClass() == IBioMiniDevice.ScannerClass.UNIVERSIAL_DEVICE) {
                    // capture fingerprint image
                    mCurrentDevice.captureSingle(option,
                            new CaptureResponder() {
                                @Override
                                public boolean onCaptureEx(final Object context, final Bitmap capturedImage,
                                                           final IBioMiniDevice.TemplateData capturedTemplate,
                                                           final IBioMiniDevice.FingerState fingerState) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Log.d(TAG,"onCaptureEx");
                                            if (capturedImage != null) {
                                                Log.d(TAG,"capturedImage");
                                                ImageView iv = (ImageView) findViewById(R.id.imageView1);
                                                if (iv != null) {
                                                    iv.setImageBitmap(capturedImage);
                                                }
                                            }
                                        }
                                    });
                                    if (capturedTemplate != null) {
                                        boolean isMatched = false;
                                        String matchedID = "";
                                        String matchedfirstname="";
                                        String matchedlastname="";
                                        for (UserData ud : mUsers) {
                                            if (mCurrentDevice.verify(
                                                    capturedTemplate.data, capturedTemplate.data.length,
                                                    ud.template, ud.template.length)) {
                                                isMatched = true;
                                                matchedID = ud.userid;
                                                break;
                                            }
                                        }
                                        if (isMatched) {

                                            Log.d(TAG,"Match found : " + matchedID+" "+matchedfirstname+" "+matchedlastname);
                                            Log.d(TAG,getResources().getText(R.string.verify_ok).toString());
                                            ((TextView)findViewById(R.id.user_id_search)).setText(matchedID);
                                            ((TextView)findViewById(R.id.textViewMessage)).setText(getResources().getText(R.string.verify_ok));
                                        } else {
                                            Log.d(TAG,"No match found : ");
                                            Log.d(TAG,getResources().getText(R.string.verify_not_match).toString());
                                            ((TextView)findViewById(R.id.user_id_search)).setText("");

                                            ((TextView)findViewById(R.id.textViewMessage)).setText(getResources().getText(R.string.verify_not_match));
                                        }
                                    } else {
                                        Log.d(TAG,"<<ERROR>> Template is not extracted...");
                                        Log.d(TAG,getResources().getText(R.string.verify_fail).toString());
                                        ((TextView)findViewById(R.id.user_id_search)).setText("");

                                        ((TextView)findViewById(R.id.textViewMessage)).setText(getResources().getText(R.string.verify_fail));
                                    }
                                    return true;
                                }

                                @Override
                                public void onCaptureError(Object context, int errorCode, String error) {
                                    Log.d(TAG,"onCaptureError : " + error);
                                    Log.d(TAG,getResources().getText(R.string.capture_fail).toString());
                                }
                            }, true);
                }else if (mCurrentDevice.getDeviceInfo().scannerType.getDeviceClass() == IBioMiniDevice.ScannerClass.HID_DEVICE) {

                    UserData _user = mUsers.get(mUsers.size()-1);
                    if(mCurrentDevice.verify(_user.template , null)) { // HID Device does not supported verify with two templates.
                       // Log.d(TAG,"Match found : " + _user.userid+" "+_user.first_name+" "+_user.last_name);
                        Log.d(TAG,getResources().getText(R.string.verify_ok).toString());
                    }else {
                        IBioMiniDevice.ErrorCode _ecode =  mCurrentDevice.getLastError();
                        Log.d(TAG,_ecode.toString()  + "("+_ecode.value()  +")");
                        Log.d(TAG,getResources().getText(R.string.verify_not_match).toString());
                    }
                }
            }

        }

        if (currentPage == ENROLLPAGE) {
            if (mCurrentDevice != null) {
                final String userid = ((EditText) findViewById(R.id.user_id)).getText().toString();

                if (userid.equals("")){//||userfirstname.equals("")||userlastname.equals("")) {
                    Log.d(TAG,"<<ERROR>> There is no user name");
                    Toast.makeText(getApplicationContext(),"There is no user name or ID",Toast.LENGTH_LONG).show();
                    return;
                }
                ((ImageView) findViewById(R.id.imageView_enroll)).setImageBitmap(null);
                IBioMiniDevice.CaptureOption option = new IBioMiniDevice.CaptureOption();
                option.extractParam.captureTemplate = true;
                option.captureTemplate = true; //deprecated
                //option.frameRate = IBioMiniDevice.FrameRate.ELOW;
                // capture fingerprint image
                mCurrentDevice.captureSingle(option,
                        new CaptureResponder() {
                            @Override
                            public boolean onCaptureEx(final Object context, final Bitmap capturedImage,
                                                       final IBioMiniDevice.TemplateData capturedTemplate,
                                                       final IBioMiniDevice.FingerState fingerState) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if(capturedImage != null) {
                                            ImageView iv = (ImageView) findViewById(R.id.imageView_enroll);
                                            if(iv != null) {
                                                iv.setImageBitmap(capturedImage);
                                            }
                                        }
                                    }
                                });
                                if(capturedTemplate != null) {
                                    mUsers.add(new UserData(userid, capturedTemplate.data, capturedTemplate.data.length));
                                    ContentValues cv = new ContentValues();
                                    cv.put("name",userid);
                                    cv.put("fpdata",capturedTemplate.data);
                                    db.insert("tablename",null,cv);
                                    Log.d(TAG,getResources().getText(R.string.enroll_ok).toString());
                                    ((TextView)findViewById(R.id.textViewMessage_enroll)).setText(getResources().getText(R.string.enroll_ok));
                                    ((EditText) findViewById(R.id.user_id)).setText("");
                                }
                                else {
                                    Log.d(TAG,"<<ERROR>> Template is not extracted...");
                                    Log.d(TAG,getResources().getText(R.string.enroll_fail).toString());
                                    ((TextView)findViewById(R.id.textViewMessage_enroll)).setText("Template is not extracted");
                                }
                                Log.d(TAG,((IBioMiniDevice)context).popPerformanceLog());

                                return true;
                            }

                            @Override
                            public void onCaptureError(Object context, int errorCode, String error) {
                                Log.d(TAG,"onCaptureError : " + error);
                                Log.d(TAG,getResources().getText(R.string.enroll_fail).toString());
                                ((TextView)findViewById(R.id.textViewMessage_enroll)).setText("onCaptureError : " + error);
                            }
                        }, true);


            }
        }
    }

    public void closeDeviceAndFinishActivity()
    {
        Log.d(TAG, "closeDeviceAndFinishActivity");
    }

    void handleDevChange(IUsbEventHandler.DeviceChangeEvent event, Object dev) {
        if (event == IUsbEventHandler.DeviceChangeEvent.DEVICE_ATTACHED && mCurrentDevice == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int cnt = 0;
                    while (mBioMiniFactory == null && cnt < 20) {
                        SystemClock.sleep(1000);
                        cnt++;
                    }
                    if (mBioMiniFactory != null) {
                        mCurrentDevice = mBioMiniFactory.getDevice(0);

                        Log.d(TAG, "mCurrentDevice attached : " + mCurrentDevice);
                        if (mCurrentDevice != null /*&& mCurrentDevice.getDeviceInfo() != null*/) {
                            Log.d(TAG," DeviceName : " + mCurrentDevice.getDeviceInfo().deviceName);
                            Log.d(TAG,"         SN : " + mCurrentDevice.getDeviceInfo().deviceSN);
                            Log.d(TAG,"SDK version : " + mCurrentDevice.getDeviceInfo().versionSDK);
                        }
                    }
                }
            }).start();
        } else if (mCurrentDevice != null && event == IUsbEventHandler.DeviceChangeEvent.DEVICE_DETACHED && mCurrentDevice.isEqual(dev)) {

            Log.d(TAG, "mCurrentDevice removed : " + mCurrentDevice);
            mCurrentDevice = null;
        }
    }

    void restartBioMini() {
        Log.d(TAG,"restartBioMini");
        if(mBioMiniFactory != null) {
            mBioMiniFactory.close();
        }
        if( mbUsbExternalUSBManager ){
            mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
            mBioMiniFactory = new BioMiniFactory(mainContext, mUsbManager){
                @Override
                public void onDeviceChange(DeviceChangeEvent event, Object dev) {
                    Log.d(TAG,"----------------------------------------");
                    Log.d(TAG,"onDeviceChange : " + event + " using external usb-manager");
                    Log.d(TAG,"----------------------------------------");
                    handleDevChange(event, dev);
                }
            };
            //
            mPermissionIntent = PendingIntent.getBroadcast(this,0,new Intent(ACTION_USB_PERMISSION),0);
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            registerReceiver(mUsbReceiver, filter);
            checkDevice();
        }else {
            Log.d(TAG,"restartBioMini BioMiniFactory");
            mBioMiniFactory = new BioMiniFactory(mainContext) {
                @Override
                public void onDeviceChange(DeviceChangeEvent event, Object dev) {
                    Log.d(TAG,"----------------------------------------");
                    Log.d(TAG,"onDeviceChange : " + event);
                    Log.d(TAG,"----------------------------------------");
                    handleDevChange(event, dev);
                }
            };
        }
        //mBioMiniFactory.setTransferMode(IBioMiniDevice.TransferMode.MODE2);
    }
    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver(){
        public void onReceive(Context context,Intent intent){
            String action = intent.getAction();
            if(ACTION_USB_PERMISSION.equals(action)){
                synchronized(this){
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
                        if(device != null){
                            if( mBioMiniFactory == null) return;
                            mBioMiniFactory.addDevice(device);
                            Log.d(TAG,String.format(Locale.ENGLISH ,"Initialized device count- BioMiniFactory (%d)" , mBioMiniFactory.getDeviceCount() ));
                        }
                    }
                    else{
                        Log.d(TAG, "permission denied for device"+ device);
                    }
                }
            }
        }
    };
    public void checkDevice(){
        if(mUsbManager == null) return;
        Log.d(TAG,"checkDevice");
        HashMap<String , UsbDevice> deviceList = mUsbManager.getDeviceList();
        Iterator<UsbDevice> deviceIter = deviceList.values().iterator();
        while(deviceIter.hasNext()){
            UsbDevice _device = deviceIter.next();
            if( _device.getVendorId() ==0x16d1 ){
                //Suprema vendor ID
                mUsbManager.requestPermission(_device , mPermissionIntent);
            }else{
            }
        }
    }

    private void set_fp_powerEnabled(boolean enabled) {
        AccessoryPower.setPower(this, AccessoryPower.AccessoryType.FINGERPRINTER, enabled);
    }
}
