package sto.android.app;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.action.actionmdm.MDMApi;
import com.action.actionscaner.ScanerApi;

public class KaicomH702JNI implements StoJNI {

    private static final String TAG = "kaicomH702";

    public static final String ACTION_SCANER = "com.action.actionscaner.SCAN_RESULT";
    private static final String DEFAULT_OPEN = "default_open";

    private final Context context;
    private ScanerApi scanerApi;
    private ScanCallBack callback;
    private MDMApi mdmApi;

    public static boolean isH702() {
        return Build.MODEL.equalsIgnoreCase("H702");
    }

    private static volatile KaicomH702JNI INSTANCE;

    private KaicomH702JNI(Context context) {
        this.context = context;
        mdmApi = new MDMApi(context);
        this.scanerApi = new ScanerApi(context);
        IntentFilter intentFilter = new IntentFilter(ACTION_SCANER);
        Receiver receiver = new Receiver();
        this.context.getApplicationContext().registerReceiver(receiver, intentFilter);
    }

    public static KaicomH702JNI getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (KaicomH702JNI.class) {
                if (INSTANCE == null) {
                    INSTANCE = new KaicomH702JNI(context.getApplicationContext());
                }
            }
        }
        return INSTANCE;
    }

    private class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_SCANER.equals(intent.getAction())) {
                if (callback != null) {
                    String result = intent.getStringExtra("scanResult");
                    int type = intent.getIntExtra("type", -1);
                    callback.onScanResults(result);
                    callback.onScanResults(result, type);
                }
            }
        }
    }

    @Override
    public int getPlatform() {
        if (isH702()) {
            return 11;
        }
        return -1;
    }

    @Override
    public String getJniVer() {
        if (isH702()) {
            return "1.0";
        }
        return "";
    }

    @Override
    public int getEventFuction(int keycode) {
        switch (keycode) {
            case KeyEvent.KEYCODE_MENU:// 82
                return StoPdaKeyEvent.KEYCODE_MENU;
            // Home（Touch Key）
            case KeyEvent.KEYCODE_HOME:// 3
                return StoPdaKeyEvent.KEYCODE_HOME;
            // Back（Touch Key）
            case KeyEvent.KEYCODE_BACK:// 4
                return StoPdaKeyEvent.KEYCODE_BACK;
            case KeyEvent.KEYCODE_BUTTON_MODE:// 110
                // LeftScan
            case KeyEvent.KEYCODE_BUTTON_L1:// 102
                // RightScan
            case KeyEvent.KEYCODE_BUTTON_R1:// 103
                return StoPdaKeyEvent.KEYCODE_SCAN;
            default:
                return keycode;
        }
    }

    @Override
    public String getPdaBrand() {
        return "kaicomH702";
    }

    @Override
    public void setmScanCB(ScanCallBack mScanCB) {
        this.callback = mScanCB;
    }

    @Override
    public void SetGPIOStatusJNI(int gpio, int status) {
        // nonsupport
    }

    @Override
    public void SetScannerOn() {
        scanerApi.setAutoInput(false);
        scanerApi.setEnableScaner(true);
    }

    @Override
    public void SetScannerStart() {
        scanerApi.scan();
    }

    @Override
    public void SetScannerStop() {
        // nonsupport
    }

    @Override
    public void SetScannerOff() {
        scanerApi.setEnableScaner(false);
    }

    @Override
    public int SetScannerPara(int para, int value) {
        return -1;
    }

    @Override
    public int GetScannerPara(int para) {
        return -1;
    }

    @Override
    public String SetScannerPara(String para, String value) {
        return "-1";
    }

    @Override
    public String GetScannerPara(String para) {
        return "-1";
    }

    @Override
    public void SetScannerRetriger() {
        // nonsupport
    }

    @Override
    public void SetScannerTimerOut(int sec) {
        // nonsupport
    }

    @Override
    public boolean GetScannerIsScanning() {
        return false;
    }

    @Override
    public int getmScanModel() {
        return 10;
    }

    @Override
    public void SetSystemReboot() {
        mdmApi.reboot();
    }

    @Override
    public void SetSystemShutdown() {
        mdmApi.shutdown();
    }

    @Override
    public void SetSystemTime(String mm) {
        try {
            mdmApi.setTime(Long.parseLong(mm));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void SetMachineCode(String code) {
        writeSn(code);
    }

    @Override
    public String GetMachineCode() {
        return readSN();
    }

    @Override
    public void disableKeypad() {
        // nonsupport
    }

    public static final String KAICOM_DISABLE_KEYPAD = "com.kaicom.disable_keypad";
    public static final String KAICOM_DISABLE_KEYPAD_STRING = "kaicom_disable_keypad_string";

    @Override
    public void disableKeypadEnableCustom(String customstr) {
        Intent intent = new Intent(KAICOM_DISABLE_KEYPAD);
        intent.putExtra(KAICOM_DISABLE_KEYPAD, true);
        intent.putExtra(KAICOM_DISABLE_KEYPAD_STRING, customstr);
        context.sendBroadcast(intent);

    }

    @Override
    public void enableKeypad() {
        // nonsupport
    }

    @Override
    public void enableKeydownTone() {
        // nonsupport
    }

    @Override
    public int GetStatusKeydownTone() {
        return 1;
    }

    @Override
    public void disableKeydownTone() {
        // nonsupport
    }

    @Override
    public void TurnOffStatusBarExpand() {
        mdmApi.setDisableStatusBar(true);
    }

    @Override
    public int GetStatusBarExpand() {
        return mdmApi.isDisableStatusBar() ? 0 : 1;
    }

    @Override
    public void TurnOnStatusBarExpand() {
        mdmApi.setDisableStatusBar(false);
    }

    @Override
    public void TurnOffUSBDebug() {
        mdmApi.setAdbEnable(false);
    }

    @Override
    public int GetStatusUSBDebug() {
        return mdmApi.hasAdbEnable() ? 1 : 0;
    }

    @Override
    public void TurnOnUSBDebug() {
        mdmApi.setAdbEnable(true);
    }

    @Override
    public void TurnOffInstallManager() {
        // nonsupport
    }

    @Override
    public int GetStatusInstallManager() {
        return 1;
    }

    @Override
    public void TurnOnInstallManager() {
        // nonsupport
    }

    @Override
    public void TurnOnScreenLock() {
        // nonsupport
    }

    @Override
    public int GetStatusScreenLock() {
        return 1;
    }

    @Override
    public void TurnOffScreenLock() {
        // nonsupport
    }

    @Override
    public int GetStatusWakeUp() {
        return 1;
    }

    @Override
    public void CfgPowerKeyWakeUp() {
        // nonsupport
    }

    @Override
    public void CfgAnyKeyWakeUp() {
        // nonsupport
    }

    @Override
    public void Disable_touch_screen() {
        // nonsupport
    }

    @Override
    public void Enable_touch_screen() {
        // nonsupport
    }

    @Override
    public int GetStatusTouch_screen() {
        return 1;
    }

    @Override
    public void StoJNI_InstallApkWithSilence(String apkPath, boolean runAfterFinished) {
        mdmApi.install(apkPath, runAfterFinished);
    }

    @Override
    public void TurnOnOffGPS(boolean set) {
        // nonsupport
    }

    @Override
    public void TurnOnOffBrowser(boolean set) {
        // nonsupport
    }

    @Override
    public void Disable_home_touch_screen() {
        mdmApi.setVirtualKeyEnable("home", false);
    }

    @Override
    public void Enable_home_touch_screen() {
        mdmApi.setVirtualKeyEnable("home", true);
    }

    @Override
    public int GetStatusTouch_Home_screen() {
        return mdmApi.hasVirtualKeyEnable("home") ? 1 : 0;
    }

    @Override
    public void Disable_menu_touch_screen() {
        mdmApi.setVirtualKeyEnable("menu", false);
        mdmApi.setVirtualKeyEnable("app_switch", false);

    }

    @Override
    public void Enable_menu_touch_screen() {
        mdmApi.setVirtualKeyEnable("menu", true);
        mdmApi.setVirtualKeyEnable("app_switch", true);
    }

    @Override
    public int GetStatusTouch_Menu_screen() {
        return mdmApi.hasVirtualKeyEnable("menu") ? 1 : 0;
    }

    @Override
    public void Disable_back_touch_screen() {
        mdmApi.setVirtualKeyEnable("back", false);
    }

    @Override
    public void Enable_back_touch_screen() {
        mdmApi.setVirtualKeyEnable("back", true);
    }

    @Override
    public int GetStatusTouch_Back_screen() {
        return mdmApi.hasVirtualKeyEnable("back") ? 1 : 0;
    }

    @Override
    public void modifyAudio() {
        // TODO
    }

    @Override
    public void setRegister() {
        // TODO
    }

    @SuppressLint("Recycle")
    @TargetApi(24)
    private void writeSn(String sn) {
        if (TextUtils.isEmpty(sn))
            throw new IllegalArgumentException("sn must be assign a valid value");

        Uri URI_SN_OP = Uri.parse("content://cn.kaicom.apiservice.sn");
        ContentResolver resolver = context.getContentResolver();
        ContentProviderClient client = resolver.acquireContentProviderClient(URI_SN_OP);
        if (client == null) {
            throw new RuntimeException("can not write SN from H702");
        }

        try {
            // 第二个参数 arg 传入待写入的 sn
            client.call("write_sn", sn, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        } finally {
            client.close();
        }
    }

    @SuppressLint("Recycle")
    @TargetApi(24)
    private String readSN() {
        Uri uri = Uri.parse("content://cn.kaicom.apiservice.sn");
        String readsn = "";

        ContentResolver resolver = context.getContentResolver();
        ContentProviderClient client = resolver.acquireContentProviderClient(uri);
        if (client == null) {
            throw new RuntimeException("can not read SN from H702");
        }

        try {
            Bundle bundle = client.call("read_sn", null, null);
            if (bundle != null) {
                readsn = bundle.getString("sn");
                Log.d(TAG, "readsn:" + readsn);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            Log.e(TAG, "readSN", e);
        } finally {
            client.close();
        }

        if ("null".equalsIgnoreCase(readsn)) {
            return "";
        }

        return readsn;
    }


}
