const common = require('../common.js');

const readServiceID = '0000FEE7-0000-1000-8000-00805F9B34FB';
const readID = '000036F6-0000-1000-8000-00805F9B34FB';
const writeServiceID = '0000FEE7-0000-1000-8000-00805F9B34FB';
const writeID = '000036F5-0000-1000-8000-00805F9B34FB';
const MTU = 115;

function acceptDevice(device) {
    return device.btid ? true : false;
}

function isSingleBt() {
    return true;
}

function isDevice(device, data) {
    const advertisData = new Uint8Array(data.advertisData);
    const mac = device.btid
        .split('')
        .map((p, i) => parseInt(p + device.btid[i + 1], 16))
        .filter((p, i) => i % 2 == 0);

    if (advertisData.slice(0, 4).toString() == [0x09, 0xff, 0x01, 0x02].toString() && advertisData.slice(4, 10).toString() == mac.toString()) {
        return true;
    }

    return false;
}

function sendCommand(cmd, data = []) {
    data = [cmd, data.length].concat(data);
    return common.completArrayCRC(data, data.length);
} // 鉴权

function alterConnect(device, deviceId) {
    return [sendCommand(0x01, [0xab, 0xcd, 0xab, 0xcd])];
}

function readData(device, value, data) {
    var value = new Uint8Array(value);
    console.log(value);

    switch (value[0]) {
        case 0x44:
            data.voltage = (((value[2] << 8) | value[3]) / 100).toFixed(2);
            break;

        case 0x42:
            //data = FMBMS.BMSReply(value.slice(2, 2 + value[1]), data)
            break;
    }

    return data;
}

function stateUpdate(device, deviceId) {
    // console.log('读电压')
    return [sendCommand(0x04)];
}

function turnOn(device, deviceId) {
    console.log('通电');
    return [sendCommand(0x03, [0xaa])];
}

function turnOff(device, deviceId) {
    console.log('断电');
    return [sendCommand(0x03, [0xbb])];
}

module.exports = {
    readServiceID: readServiceID,
    readID: readID,
    writeServiceID: writeServiceID,
    writeID: writeID,
    MTU: MTU,
    acceptDevice: acceptDevice,
    isDevice: isDevice,
    alterConnect: alterConnect,
    readData: readData,
    stateUpdate: stateUpdate,
    turnOn: turnOn,
    turnOff: turnOff,
    isSingleBt: isSingleBt
};
