const minimist = require('minimist')
const WS = require('websocket').w3cwebsocket
const { v4: uuidv4 } = require('uuid')

/**
 *  connector creating client and routing to handlers
 *
 *  @author Björn Hase
 *  @license https://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
 *  @link https://gitea.node001.net/HerrHase/potato-launcher.git
 *
 */
class Connector {

    /**
     *  getting
     *
     *
     *  @param {object} handlers
     *
     */
    constructor(handlers) {

        this.handlers = handlers

        // getting arguments
        const argv = minimist(process.argv.slice(2))

        this.NL_PORT = argv['nl-port']
        this.NL_TOKEN = argv['nl-token']
        this.NL_EXTID = argv['nl-extension-id']

        // create socket connection for receive and send events
        this.client = new WS(`ws://localhost:${this.NL_PORT}?extensionId=${this.NL_EXTID}`)

        // add events for on message to
        this.client.onmessage = (event) => {
            this.handleMessage(event)
        }
    }

    /**
     *  send to app
     *
     *  @param  {string} eventName
     *  @param  {array} data
     *
     */
    send(eventName, data) {
        this.client.send(JSON.stringify({
            id: uuidv4(),
            method: 'app.broadcast',
            accessToken: this.NL_TOKEN,
            data: {
                event: eventName,
                data: data
            }
        }))
    }

    /**
     *  handle messages from app
     *
     *  @param {object} event
     *
     */
    handleMessage(event) {
        if (typeof event.data === 'string') {

            // parse message
            const message = JSON.parse(event.data)

            // if event is in handlers-object mapped call it
            if (this.handlers.hasOwnProperty(message.event)) {
                this.handlers[message.event].call(null, this, message.data)
            }
        }
    }
}

module.exports.Connector = Connector