import Logger from './logger'
import Emitter from './emitter'
import Mixin from './mixin'
import Utils from './util'
export default class VueSocket {
    constructor({ connection, vuex, options }) {
        Logger.debug = options.debug
        this.connection = connection
        this.connection_options = options
        this.init(connection, options)
        this.emitter = new Emitter(vuex)
    }

    install(Vue) {
        Vue.prototype.$vueSocket = this
        Vue.mixin(Mixin)
        Logger.info('Vue-Socket plugin enabled')
    }

    init(connection, options) {
        this.ws = new WebSocket(connection + options.path)
        this.ws.binaryType = 'arraybuffer'
        const _this = this
        this.ws.onopen = function(evt) {
            Logger.info('OPEN')
            _this.emitter.emit('connect')
        }
        this.ws.onclose = function(evt) {
            Logger.info('CLOSE')
            _this.emitter.emit('close')
        }
        this.ws.onmessage = function(evt) {
            const data = evt.data
            Logger.info('RESPONSE: ' + data)
            _this.emitter.emit('message', data)
            
        }
        this.ws.onerror = function(evt) {
            Logger.error('ERROR: ' + evt.data)
            _this.emitter.emit('error', evt.data)
        }
    }

    isConnected() {
        return this.ws && this.ws.readyState === WebSocket.OPEN
    }

    reconnect() {
        this.disconnect()
        this.init(this.connection, this.connection_options)
    }

    disconnect() {
        if (this.ws) {
            this.ws.close()
            this.ws = null
        }
    }

    send(data) {
        Logger.info('send data -> ' + Utils.byte2HexStr(data))
        this.ws.send(data)
    }
}
