import store from './store'
import * as ws from './webSocket'
import pako from 'pako'

export var scanflag = false;
// export var bleDiscovery = false;
		
export var BluetoothAdapter = null;
export var btAdapter = null;
export var Toast = null;
export var activity = null;
export var Intent = null;
export var lastRcvTime = 0;     // 最近接收心率带数据时间

var devSaveTimeArr = [];        // 各ble设备数据保存时间
var dataRcvArr = [];            // 数据接收数组
var upDataArr = [];             // 上传数据数组
var upData = null;              // 上传数据
// var upTime = 0;                 // 数据上传时间

var targetDevPreNameArr = [
    'CL831',    //小飞龙心率带 OK
    'CL880',    //带屏心率带 OK
    'CL820',    //CL820W 心率胸带 OK
    'CL837',    //扁平化心率带
];

export function getBleDiscovery() {
    // return bleDiscovery;
    return store.state.bleDiscovery;
}

export function setBleDiscovery(bleDiscovery) {
    store.commit('setBleDiscovery', bleDiscovery);
}

// 获取蓝牙状态
/* function getBluetoothState() {
    plus.bluetooth.getBluetoothAdapterState({
        success:function(e){
            console.log('获取蓝牙状态 success: '+JSON.stringify(e));
        },
        fail:function(e){
            console.log('获取蓝牙状态 failed: '+JSON.stringify(e));
        }
    });
} */

/**
 * 获取蓝牙的状态
 * @return {boolean} 是否已开启
 */
export function getBluetoothStatus() {
    if(btAdapter != null) {
        var bleEnabled = btAdapter.isEnabled();
        console.log("getBluetoothStatus: " + bleEnabled);
        return bleEnabled;
    }
    else {
        if (getBleDiscovery()) {
            setBleDiscovery(false);
        }
        shortToast("本设备不支持蓝牙");
        return false;
    }
}

export function turnOnBluetooth() {
    if(!btAdapter.isEnabled()) {
        if(activity == null) {
            shortToast("未获取到activity");
            return;
        } else {
            var intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            var requestCode = 1;
            activity.startActivityForResult(intent, requestCode);
            return;
        }
    } else {
        shortToast("蓝牙已经打开");
    }
}

function shortToast(msg) {
    Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
}

// 监听状态变化
// 回调函数参数event对象包括以下属性： 
// available - Boolean，蓝牙适配器是否可用； 
// discovering - Boolean，蓝牙适配器是否处于搜索状态。
export function listenerStateChange(){
	plus.bluetooth.onBluetoothAdapterStateChange(function(e){
		console.log('listenerStateChange: ' + JSON.stringify(e));
        if (e.available && !e.discovering && store.state.classOn > 0) {
            if (getBluetoothStatus()) {
                console.log('onBluetoothAdapterStateChange -> startBluetoothDiscovery');
                startBluetoothDiscovery();  // 开始搜索蓝牙
                console.log('onBluetoothAdapterStateChange: 已上课，开始接收心率数据');
                // shortToast('接收心率数据中...');
            }
            else {
                console.log('onBluetoothAdapterStateChange: 蓝牙未开启，无法接收心率数据(2)');
            }
        }
        else if (!e.available && e.discovering) {
            console.log('onBluetoothAdapterStateChange -> stopBluetoothDiscovery');
            setBleDiscovery(false);
            stopBluetoothDiscovery();  // 停止搜索蓝牙
            console.log('onBluetoothAdapterStateChange: 蓝牙未开启，无法接收心率数据(1)');
            // shortToast('蓝牙未开启，无法接收心率数据');
        }
	});
}

// 开始搜索蓝牙
export function startBluetoothDiscovery() {
    console.log("startBluetoothDiscovery");
    if (!ws.getWsState()) {
        ws.connect(store.state.wsUrl, store.state.eqSn);
    }

    plus.bluetooth.openBluetoothAdapter({
        success:function(e){
            console.log('openBluetoothAdapter success: '+JSON.stringify(e));
            plus.bluetooth.startBluetoothDevicesDiscovery({
                //services: null, 			// 可选 要获取设备的uuid列表
                allowDuplicatesKey: true,	// ( Boolean ) 可选 是否允许重复上报同一设备
                interval: 0,		 		// 可选 上报设备的间隔  0表示找到新设备立即上报，其他数值根据传入的间隔上报。
                success:function(e){
                    console.log('startBluetoothDevicesDiscovery success: '+JSON.stringify(e));
                    setBleDiscovery(true);
                },
                fail:function(e){
                    console.log('startBluetoothDevicesDiscovery failed: '+JSON.stringify(e));
                    setBleDiscovery(false);
                },
                // complete:function(e){    // 调用成功或失败都会触发此回调
                //     console.log('startBluetoothDevicesDiscovery complete: '+JSON.stringify(e));
                //     setBleDiscovery(false);
                // }
            });
        },
        fail:function(e){
            console.log('openBluetoothAdapter failed: '+JSON.stringify(e));
            setBleDiscovery(false);
        }
    });
}

// 停止搜索蓝牙
export function stopBluetoothDiscovery(){
    console.log("stopBluetoothDiscovery");
    if (ws.getWsState()) {        
        ws.disconnect();
    }

    plus.bluetooth.stopBluetoothDevicesDiscovery({
        success:function(e){
            console.log('stopBluetoothDevicesDiscovery success: '+JSON.stringify(e));
            plus.bluetooth.closeBluetoothAdapter({
                success:function(e){
                    console.log('closeBluetoothAdapter success: '+JSON.stringify(e));
                },
                fail:function(e){
                    console.log('closeBluetoothAdapter failed: '+JSON.stringify(e));
                }
            });
        },
        fail:function(e){
            console.log('stopBluetoothDevicesDiscovery failed: '+JSON.stringify(e));
        }
    });
}

// 监听发现新设备
export function listenerDeviceFound() {
    plus.bluetooth.onBluetoothDeviceFound(function(e){
        let devices = e.devices;
        // console.log('device found: ' + devices.length);

        let VendorID = 0;   // 厂商标识ID
        let DevType = 0;    // 设备数据类型
        let Power = 0;
        let HeartRate = 0;
        let Sn = 0;
        let now = 0;
        let waitTime = 0;
        let data = '';
        let devPreName = '';

        for(var i in devices) {
            devPreName = devices[i].name.substr(0,5);
            if (targetDevPreNameArr.includes(devPreName)) {
                // console.log(i+': '+JSON.stringify(devices[i]));
                // console.log('advertisServiceUUIDs: ' + devices[i].advertisServiceUUIDs);
                // console.log('localName: ' + devices[i].localName);
                // console.log('advertisData: ' + buf2hex(devices[i].advertisData));
                // console.log('serviceData: ' + buf2hex(devices[i].serviceData));

                VendorID = parseInt(new Uint16Array(devices[i].advertisData, 0, 2));
                DevType = parseInt(new Uint8Array(devices[i].advertisData, 2, 1));
                
                // DevType == 0xa1 [新版] CL831 中性版本 RSP 广播
                // DevType == 0xa2 [新版] CL837 中性版本 RSP 广播
                if (VendorID == 0xff04 && (DevType == 0xa1 || DevType == 0xa2)) {
                    Power = parseInt(new Uint8Array(devices[i].advertisData, 8, 1));
                    HeartRate = parseInt(new Uint8Array(devices[i].advertisData, 7, 1));
                    Sn = parseInt(devices[i].localName.substr(6, devices[i].localName.length));
                }
                else {  // [老版]
                    Power = parseInt(new Uint8Array(devices[i].advertisData, 3, 1));
                    HeartRate = parseInt(new Uint8Array(devices[i].advertisData, 5, 1));
                    Sn = parseInt(devices[i].localName.substr(6, devices[i].localName.length));
                }
                // console.log('VendorID: ' + VendorID + ' DevType: ' + DevType + ' Sn: ' + Sn + '  localName: ' + devices[i].localName + '  HeartRate: ' + HeartRate + '  Power: ' + Power + '  advertisData: ' + buf2hex(devices[i].advertisData));

                now = new Date().getTime(); //毫秒
                lastRcvTime = now;  // 最近接收心率带数据时间

                if (devSaveTimeArr[Sn] == undefined)
                    devSaveTimeArr[Sn] = 0;
                
                waitTime = now - devSaveTimeArr[Sn];
                // console.log("devSaveTimeArr["+ Sn + "]: " + devSaveTimeArr[Sn] + " waitTime: " + waitTime);
                if (waitTime >= 1500) { // 同一个设备，上报时间间隔为1.5秒
                    // console.log("[upData] waitTime: " + waitTime);
                    devSaveTimeArr[Sn] = now;

                    data = {
                        "sn": Sn,
                        "hr": HeartRate,
                        "pw": Power
                    };
                    dataRcvArr.push(data);
                }                
            }
            // else {
            //     console.log(i+': '+JSON.stringify(devices[i]));
            // }
        }
    });
}

export function uploadBleData() {
    if (dataRcvArr.length == 0)
        return;
    
    upDataArr = deepClone(dataRcvArr);
    dataRcvArr = [];   //清空缓冲区
    upData = JSON.stringify(upDataArr);
    // console.log("[uploadBleData] Data (len: " + upData.length+ "): " + upData);
    upData = dealUpData(upData);
    // console.log("[uploadBleData] Data GZip len: " + upData.length);
    if (ws.getWsState()) {
        ws.sendData(upData);
    }
    else {
        ws.connect(store.state.wsUrl, store.state.eqSn);
    }
}

function dealUpData(data) {
    if (data == "") 
        return;
    // var binaryString = pako.gzip(data, { to: 'string' });   //压缩
    var binaryString = pako.gzip(data);   //压缩
    return binaryString;
}

export function test() {
    // ws.connect(store.state.wsUrl, store.state.eqSn);
    ws.connect('ws://localhost:8080/websocket', '7962ad082220d997');
}

// function turnOnBleAdv(obj) {
//     if(!getBluetoothStatus()) {
//         turnOnBluetooth();
//         return;
//     }
    
//     if (!scanflag) {
//         obj.innerHTML = "关闭蓝牙广播"
//         scanflag = true;
//         startBluetoothDiscovery();
//     }
//     else {
//         obj.innerHTML = "打开蓝牙广播"
//         scanflag = false;
//         stopBluetoothDiscovery();
//     }    
// }

export function buf2hex(buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
