package sto.android.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.DeviceManager;
import android.device.ScanManager;
import android.device.Stojni;
import android.util.Log;
import android.view.KeyEvent;
/**Created by lenovo on 2016/4/29<br/>
 * 提示：<br/>
 * 1.必须调用close()进行释放<br/>
 */
public class UboxunJNI implements StoJNI {
    private static UboxunJNI uboxunJNI;
    private static String TAG = "uboxunJNI";
    private final String SCAN_ACTION = "urovo.rcv.message";
    private final String Extra_BarcodeType = "barcodeType";
    private final String Extra_Barcode = "barocode";
    private final String Extra_Length = "length";

    private ScanManager scanMgr;
    private DeviceManager dvcMgr;
    private BroadcastReceiver receiver;
    private Context ctx;
    private String charset;
    private ScanCallBack scanCallback;
    Stojni Sto_jni;
    private UboxunJNI(Context ctx) {
        this.scanMgr = new ScanManager();
        this.dvcMgr = new DeviceManager();
        this.receiver = new ScanDataReceiver();
        this.charset = "UTF-8";
        this.ctx = ctx;

        this.scanMgr.switchOutputMode(0);
         Sto_jni=new Stojni();


        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);
        this.ctx.registerReceiver(receiver, filter);
    }

    public static synchronized UboxunJNI getInstance(Context context) {
        if (uboxunJNI == null) {
            uboxunJNI = new UboxunJNI(context);
        }
        return uboxunJNI;
    }

    /**对扫描到的条码，用指定的字符集解析
     * @param charset
     */
    public void SetScannerCharset(String charset) {
        this.charset = charset;
    }

    /**
     * 设置回调接口
     *
     * @param mScanCB
     */
    @Override
    public void setmScanCB(ScanCallBack mScanCB) {
        this.scanCallback = mScanCB;
    }

    /**关闭UrovoDevice，释放资源
     */
    public void Close() {
        ctx.unregisterReceiver(receiver);
        scanMgr = null;
        dvcMgr = null;
        receiver = null;
        ctx = null;
    }

    @Override
    public void SetScannerOn() {
//        scanMgr.openScanner();
        Sto_jni.SetScannerOn();
    }

    @Override
    public void SetScannerStart() {
        //scanMgr.stopDecode();
//        try{
//            if(start_scan_flag){
//                scanMgr.startDecode();
//                start_scan_flag = false;
//            }
//            else{
//                scanMgr.stopDecode();
//                start_scan_flag = true;
//            }
//        }
//        catch(Exception e){
//            e.printStackTrace();
//        }
        Sto_jni.SetScannerStart();
    }

    @Override
    public void SetScannerStop() {
//        scanMgr.stopDecode();
        Sto_jni.SetScannerStop();
    }

    @Override
    public void SetScannerOff() {
//        scanMgr.closeScanner();
        Sto_jni.SetScannerOff();
    }

    @Override
    public int SetScannerPara(int para, int value) {
//        return scanMgr.setParameterInts(new int[]{para}, new int[]{value});
        return  Sto_jni.SetScannerPara(para,value);
    }

    @Override
    public String SetScannerPara(String para, String value) {
        //TODO 暂时无法实现
     return   Sto_jni.SetScannerPara(para,value);
//       return null;
    }

    @Override
    public int GetScannerPara(int para) {
//        int[] result = scanMgr.getParameterInts(new int[]{para});
//        if(result != null && result.length > 0) {
//            return result[0];
//        }
//        else {
//            return -1;
//        }
        return Sto_jni.GetScannerPara(para);
    }

    /**
     * 获取扫描头参数
     */
    @Override
    public String GetScannerPara(String para) {
        //TODO 暂时无法实现
//        return null;
        return Sto_jni.GetScannerPara(para);
    }

    @Override
    public void SetScannerRetriger() {
//        SetScannerStart();
         Sto_jni.SetScannerRetriger();
    }

    /**设置扫描超时时间（1-9秒）
     * @param sec 单位为秒
     */
    @Override
    public void SetScannerTimerOut(int sec) {
        Sto_jni.SetScannerTimerOut(sec);
//        if(sec < 1 || sec  > 9) {
//            sec = 3;
//        }
//        scanMgr.setParameterInts(new int[]{PropertyID.LASER_ON_TIME}, new int[]{sec * 10});
    }

    @Override
    public int getmScanModel() {
//        return MODEL_SE955;
//        Sto_jni.
       return  Sto_jni.getmScanModel();
    }

    @Override
    public boolean GetScannerIsScanning() {
        //TODO 暂时无法实现
        return Sto_jni.GetScannerIsScanning();
    }

    @Override
    public void SetGPIOStatusJNI(int gpio, int status) {
        Sto_jni.SetGPIOStatus(gpio,status);
//        if(gpio == GPIO_VIBRATE) {
//            if(status == GPIO_ON) {
//
//            }
//            else if(status == GPIO_OFF) {
//
//            }
//        }
//        else if(gpio == GPIO_CAMFLASH) {
//            if(status == GPIO_ON) {
//
//            }
//            else if(status == GPIO_OFF) {
//
//            }
//        }
    }

    /**
     * 系统重启
     */
    @Override
    public void SetSystemReboot() {
        Sto_jni.SetSystemReboot();
    }

    /**
     * 系统关机
     */
    @Override
    public void SetSystemShutdown() {
//        @TODO
        Sto_jni.SetSystemShutdown();
    }

    @Override
    public void SetSystemTime(String mm) {
        //dvcMgr.setCurrentTime(Long.valueOf(mm));
        Sto_jni.SetSystemTime(mm);
    }

    /**
     * 设置机唯一码（暂不实现）
     */
    @Override
    public void SetMachineCode(String code) {
        Sto_jni.SetMachineCode(code);
    }

    /**
     * 获取唯一码
     */
    @Override
    public String GetMachineCode() {
        String dvcID = "5"+Sto_jni.GetMachineCode();
        return dvcID;
    }

    /**
     * 屏蔽物理按键(扫描键除外)
     */
    @Override
    public void disableKeypad() {
        Sto_jni.disableKeypad();
    }

    /**
     * 自定义屏蔽物理按键参数String：要屏蔽的按键 以逗号隔开
     * 例如屏蔽menu键和方向上键
     * eg："+android.view.KeyEvent.KEYCODE_MENU+","+android.view.KeyEvent.KEYCODE_DPAD_UP+"
     */
    @Override
    public void disableKeypadEnableCustom(String customstr) {
        Sto_jni.disableKeypadEnableCustom(customstr);
    }

    /**
     * 使能物理按键（所有按键）
     */
    @Override
    public void enableKeypad() {
        Sto_jni.enableKeypad();
    }

    /**
     *使能物理按键音
     */
    @Override
    public void enableKeydownTone() {
        Sto_jni.enableKeydownTone();
    }

    /**
     * 获取物理按键音状态
     */
    @Override
    public int GetStatusKeydownTone() {
        return Sto_jni.GetStatusKeydownTone();
    }

    /**
     * 关闭物理按键音
     */
    @Override
    public void disableKeydownTone() {
        Sto_jni.disableKeydownTone();
    }

    private boolean isStatusBarExpand = true;

    @Override
    public void TurnOnStatusBarExpand() {
//        dvcMgr.enableStatusBar(true);
//        isStatusBarExpand = true;
        Sto_jni.TurnOnStatusBarExpand();
    }

    @Override
    public void TurnOffStatusBarExpand() {
//        dvcMgr.enableStatusBar(false);
//        isStatusBarExpand = false;
        Sto_jni.TurnOffStatusBarExpand();
    }

    /**
     * 获取状态栏是否可下拉
     */
    @Override
    public int GetStatusBarExpand() {
       return  Sto_jni.GetStatusBarExpand();
//        if(isStatusBarExpand){
//            return 1;
//        }
//        return 0;
    }

    /**
     * 使能usb debug
     * 说明：打开usb调试功能
     */
    @Override
    public void TurnOnUSBDebug() {
        Sto_jni.TurnOnUSBDebug();
    }

    /**
     * 屏蔽USB debug
     * 说明：关闭usb调试功能
     */
    @Override
    public void TurnOffUSBDebug() {
        Sto_jni.TurnOffUSBDebug();
    }

    /**
     * 获取USB debug开启状态
     */
    @Override
    public int GetStatusUSBDebug() {
        return Sto_jni.GetStatusUSBDebug();
    }

    /**
     * 使能安装APK（暂不实现）
     * 说明：允许安装第三方apk
     */
    @Override
    public void TurnOnInstallManager() {
         Sto_jni.TurnOnInstallManager();
    }

    /**
     * 屏蔽安装APK（暂不实现）
     * 说明：不允许安装第三方apk
     */
    @Override
    public void TurnOffInstallManager() {
        Sto_jni.TurnOffInstallManager();
    }

    /**
     * 获取是否屏蔽安装APK（暂不实现）
     */
    @Override
    public int GetStatusInstallManager() {
        return 0;
    }

    /**
     * 使能触摸解锁
     * 说明：恢复触摸解锁
     */
    @Override
    public void TurnOnScreenLock() {
        Sto_jni.TurnOnScreenLock();
    }

    /**
     * 禁止触摸解锁
     * 说明：待机唤醒不需要触摸解锁
     */
    @Override
    public void TurnOffScreenLock() {
        Sto_jni.TurnOffScreenLock();
    }

    /**
     * 获取屏幕是否能触摸
     * @return 1 使能解锁， 0禁止解锁
     */
    @Override
    public int GetStatusScreenLock() {
        return Sto_jni.GetStatusScreenLock();
    }

    /**
     * 配置唤醒源（暂不实现）
     * @return 1 电源键唤醒	0 任意键唤醒
     */
    @Override
    public int GetStatusWakeUp() {
        return Sto_jni.GetStatusWakeUp();
    }

    /**
     * 配置电源键唤醒（暂不实现）
     */
    @Override
    public void CfgPowerKeyWakeUp() {
         Sto_jni.CfgPowerKeyWakeUp();
    }

    /**
     * 配置任意按键唤醒（暂不实现）
     */
    @Override
    public void CfgAnyKeyWakeUp() {
        Sto_jni.CfgAnyKeyWakeUp();
    }

    /**
     * 使能触摸屏
     * 说明：恢复触摸屏触摸功能
     */
    @Override
    public void Enable_touch_screen() {
        Sto_jni.Enable_touch_screen();
    }

    /**
     * 禁止使用触摸屏
     * 说明：触摸屏去掉触摸功能
     */
    @Override
    public void Disable_touch_screen() {
        Sto_jni.Disable_touch_screen();
    }

    /**
     * 获取触摸屏是否能触摸
     */
    @Override
    public int GetStatusTouch_screen() {
        return Sto_jni.GetStatusTouch_screen();
    }

    /**
     * 静默安装apk
     * @param apkPath	为文件路径,请确保路径及文件的完整性;
     * @param runAfterFinished 为true时,Apk安装完成之后会自动运行;为false时,Apk安装完成之后不运行
     */
    @Override
    public void StoJNI_InstallApkWithSilence(String apkPath, boolean runAfterFinished) {
        Sto_jni.StoJNI_InstallApkWithSilence(apkPath,runAfterFinished);
    }

    /**
     * 开关gps
     */
    @Override
    public void TurnOnOffGPS(boolean set) {
        Sto_jni.TurnOnOffGPS(set);
    }

    /**
     * 屏蔽 / 使能 浏览器访问
     */
    @Override
    public void TurnOnOffBrowser(boolean set) {
        Sto_jni.TurnOnOffBrowser(set);
    }

    /**
     * 使用触摸屏Home键
     * 说明：恢复触摸屏Home键触摸功能
     */
    @Override
    public void Enable_home_touch_screen() {
        Sto_jni.Enable_home_touch_screen();
    }

    /**
     * 禁止使用触摸屏Home键
     * 说明：触摸屏去掉Home键触摸功能
     */
    @Override
    public void Disable_home_touch_screen() {
        Sto_jni.Disable_home_touch_screen();
    }

    /**
     * 触摸屏Home键开关，获取触摸屏上Home键的状态
     * @return 1开，0 关
     */
    @Override
    public int GetStatusTouch_Home_screen() {
//        return 0;
        return  Sto_jni.GetStatusTouch_Home_screen();
    }

    /**
     * 使用触摸屏MENU键（暂不实现）
     * 说明：恢复触摸屏MENU键触摸功能
     */
    @Override
    public void Enable_menu_touch_screen() {
        Sto_jni.Enable_menu_touch_screen();
    }

    /**
     * 禁止使用触摸屏menu键（暂不实现）
     * 说明：触摸屏去掉menu键触摸功能
     */
    @Override
    public void Disable_menu_touch_screen() {
        Sto_jni.Disable_menu_touch_screen();
    }

    /**
     * 触摸屏Menu键开关，获取触摸屏上menu键的状态（暂不实现）
     */
    @Override
    public int GetStatusTouch_Menu_screen() {
        return Sto_jni.GetStatusTouch_Menu_screen();
    }

    /**
     * 使用触摸屏BACK键（暂不实现）
     * 说明：恢复触摸屏BACK键触摸功能
     */
    @Override
    public void Enable_back_touch_screen() {
//        Sto_jni.Enable_back_touch_screen;
        Sto_jni.Enable_back_touch_screen();
    }

    /**
     * 禁止使用触摸屏back键（暂不实现）
     * 说明：触摸屏去掉back键触摸功能
     */
    @Override
    public void Disable_back_touch_screen() {
        Sto_jni.Disable_back_touch_screen();
    }

    /**
     * 触摸屏Back键开关，获取触摸屏上back键的状态（暂不实现）
     */
    @Override
    public int GetStatusTouch_Back_screen() {
        return Sto_jni.GetStatusTouch_Back_screen();
    }

    private class ScanDataReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(SCAN_ACTION.equals(intent.getAction())) {
                byte barcodeType = intent.getByteExtra(Extra_BarcodeType,(byte) 0);
                byte[] barcode = intent.getByteArrayExtra(Extra_Barcode);
                int barocodelen = intent.getIntExtra(Extra_Length,0);
                try {
                    String barcodeStr = new String(barcode, 0, barocodelen, charset);
                    if(scanCallback != null) {
                        scanCallback.onScanResults(barcodeStr, barcodeType);
                        scanCallback.onScanResults(barcodeStr);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

	@Override
	public String getPdaBrand() {
		// TODO Auto-generated method stub
		return "ubx";
	}

	@Override
	public int getEventFuction(int keycode) {
		// TODO Auto-generated method stub
		Log.d(TAG, "######"+TAG+"getEventFunction");
		switch(keycode){
		//BACK
		//Menu
		//Home
		//Upload
		//Fn
		//S1
		//SCAN
		//SCAN_LEFT
		//SCAN_RIGHT
		//S2
		//上
		//下
		//左
		//右
		//回车
		//DEL
		//Light
		//AB切换
		//num-0
		//num-1
		//num-2
		//num-3
		//num-4
		//num-5
		//num-6
		//num-7
		//num-8
		//num-9
		//num-空格
		//点.
		
				//Back
				case KeyEvent.KEYCODE_BACK:
						return StoPdaKeyEvent.KEYCODE_BACK;
				//0/空格
				case KeyEvent.KEYCODE_0:
					return StoPdaKeyEvent.KEYCODE_0;
				//num-1
				case KeyEvent.KEYCODE_1:
					return StoPdaKeyEvent.KEYCODE_1;
				//num-2
				case KeyEvent.KEYCODE_2:
					return StoPdaKeyEvent.KEYCODE_2;
				//num-3
				case KeyEvent.KEYCODE_3:
					return StoPdaKeyEvent.KEYCODE_3;
				//num-4
				case KeyEvent.KEYCODE_4:
					return StoPdaKeyEvent.KEYCODE_4;
				//num-5
				case KeyEvent.KEYCODE_5:
					return StoPdaKeyEvent.KEYCODE_5;
				//num-6
				case KeyEvent.KEYCODE_6:
					return StoPdaKeyEvent.KEYCODE_6;
				//num-7
				case KeyEvent.KEYCODE_7:
					return StoPdaKeyEvent.KEYCODE_7;
				//num-8
				case KeyEvent.KEYCODE_8:
					return StoPdaKeyEvent.KEYCODE_8;
				//num-9
				case KeyEvent.KEYCODE_9:
					return StoPdaKeyEvent.KEYCODE_9;
				//上
				case KeyEvent.KEYCODE_DPAD_UP:
					return StoPdaKeyEvent.KEYCODE_DPAD_UP;
				//下
				case KeyEvent.KEYCODE_DPAD_DOWN:
					return StoPdaKeyEvent.KEYCODE_DPAD_DOWN;
				//左
				case KeyEvent.KEYCODE_DPAD_LEFT:
					return StoPdaKeyEvent.KEYCODE_DPAD_LEFT;
				//右
				case KeyEvent.KEYCODE_DPAD_RIGHT:
					return StoPdaKeyEvent.KEYCODE_DPAD_RIGHT;
				//1-AB
				case KeyEvent.KEYCODE_ALT_LEFT:
					return StoPdaKeyEvent.KEYCODE_AB;
				//Upload
				case KeyEvent.KEYCODE_TAB:
					return StoPdaKeyEvent.KEYCODE_UP;
				//num-空格
				case KeyEvent.KEYCODE_SPACE:
					return StoPdaKeyEvent.KEYCODE_SPACE;
				//Enter
				case KeyEvent.KEYCODE_ENTER:
						return StoPdaKeyEvent.KEYCODE_ENTER;
						//Delete
				case KeyEvent.KEYCODE_DEL:
					return StoPdaKeyEvent.KEYCODE_DEL;
					//Menu
				case KeyEvent.KEYCODE_MENU:
						return StoPdaKeyEvent.KEYCODE_MENU;
						//Menu
				case KeyEvent.KEYCODE_CTRL_LEFT:
						return StoPdaKeyEvent.KEYCODE_S1;
						//Menu
				case KeyEvent.KEYCODE_CTRL_RIGHT:
						return StoPdaKeyEvent.KEYCODE_S2;
				
		
		
		//Home
		case KeyEvent.KEYCODE_HOME:
				return StoPdaKeyEvent.KEYCODE_HOME;
		//scan
		//左侧键盘
		//右侧键盘
		case KeyEvent.KEYCODE_F10:
				return StoPdaKeyEvent.KEYCODE_SCAN;
		
		//拨号
		case KeyEvent.KEYCODE_CALL:
				return StoPdaKeyEvent.KEYCODE_CALL;
		//挂机
		case KeyEvent.KEYCODE_ENDCALL:
				return StoPdaKeyEvent.KEYCODE_ENDCALL;
		
		//Fn
		case KeyEvent.KEYCODE_FUNCTION:
			return StoPdaKeyEvent.KEYCODE_FUNCTION;
		//F1
		case KeyEvent.KEYCODE_F1:
			return StoPdaKeyEvent.KEYCODE_F1;
		//F2
		case KeyEvent.KEYCODE_F2:
			return StoPdaKeyEvent.KEYCODE_F2;
		//F3
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			return StoPdaKeyEvent.KEYCODE_F3;
		//F4
		case KeyEvent.KEYCODE_VOLUME_UP:
			return StoPdaKeyEvent.KEYCODE_F4;
		//F5
		case KeyEvent.KEYCODE_F5:
			return StoPdaKeyEvent.KEYCODE_F5;
		//F6
		case KeyEvent.KEYCODE_F6:
			return StoPdaKeyEvent.KEYCODE_F6;
		//F7
		case KeyEvent.KEYCODE_F7:
			return StoPdaKeyEvent.KEYCODE_F7;
		//F8
		case KeyEvent.KEYCODE_F8:
			return StoPdaKeyEvent.KEYCODE_F8;
		//F9
		case KeyEvent.KEYCODE_F9:
			return StoPdaKeyEvent.KEYCODE_F9;
		
		
		default:return 0;
		}
	
	}

	@Override
	public String getJniVer() {
		// TODO Auto-generated method stub
		return "urovo-1.0.0.2";
	}

	@Override
	public int getPlatform() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void modifyAudio() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setRegister() {
		// TODO Auto-generated method stub
		
	}
}
