/**
 * websocket相关接口
 */
/* globals BLGlobal */
import {
    callNativeSync
} from './util';

function SocketObject(id, target) {
    this.id = id;
    this.target = target;
    return this;
}

SocketObject.prototype.close = function (options = {}) {
    try {
        this.target.close(options.code || 1000, options.reason || '');
        options &&
            options.success &&
            typeof options.success === 'function' &&
            options.success({
                errMsg: 'close:ok'
            });
        options &&
            options.complete &&
            typeof options.complete === 'function' &&
            options.complete({
                errMsg: 'close:ok'
            });
    } catch (e) {
        options &&
            options.fail &&
            typeof options.fail === 'function' &&
            options.fail({
                errMsg: 'close:fail'
            });
        options &&
            options.complete &&
            typeof options.complete === 'function' &&
            options.complete({
                errMsg: 'close:fail'
            });
    }
};

SocketObject.prototype.send = function (options = {}) {
    try {
        this.target.send(options.data);
        options &&
            options.success &&
            typeof options.success === 'function' &&
            options.success({
                errMsg: 'send:ok'
            });
        options &&
            options.complete &&
            typeof options.complete === 'function' &&
            options.complete({
                errMsg: 'send:ok'
            });
    } catch (e) {
        options &&
            options.fail &&
            typeof options.fail === 'function' &&
            options.fail({
                errMsg: 'send:fail'
            });
        options &&
            options.complete &&
            typeof options.complete === 'function' &&
            options.complete({
                errMsg: 'send:fail'
            });
    }
};

SocketObject.prototype.onClose = function (callback) {
    this.target.onclose = callback;
};

SocketObject.prototype.onOpen = function (callback) {
    this.target.onopen = callback;
};

SocketObject.prototype.onError = function (callback) {
    this.target.onerror = callback;
};

SocketObject.prototype.onMessage = function (callback) {
    this.target.onmessage = callback;
};

SocketObject.uid = 0;

export default {
    connectSocket({
        url = '',
        protocols = [],
        header = {},
        tcpNoDelay = false
    }) {
        const systemInfo = callNativeSync('getSystemInfoSync').data;
        if (systemInfo.platform === 'android') {
            return new SocketObject(
                SocketObject.uid++,
                // tcpNoDelay传了没用
                new WebSocket(url, protocols, header, tcpNoDelay)
            );
        }
        return new SocketObject(
            SocketObject.uid++,
            BLGlobal.createWebSocket(url, protocols, header, tcpNoDelay)
        );
    }
};