const connection = new WebSocket('ws://localhost:8181/socket')
// const connection = new WebSocket('wss://tronio.gltronic.ovh/socket')

export default function createSocketPlugin () {
  return store => {
    connection.onopen = function () {
      console.log('[WS] connected')
      store.dispatch('game/socketConnected')
    }

    connection.onclose = function () {
      console.log('[WS] closed')
    }

    connection.onerror = function (error) {
      console.log('[WS] error ' + error.message)
      store.dispatch('game/error', 'Connection problem')
    }

    connection.onmessage = function (message) {
      // console.log('[WS] message', message.data)

      var data = JSON.parse(message.data)

      switch (data.type) {
        case 'login':
          store.dispatch('game/login', data.message)
          break
        case 'gameSettings':
          store.dispatch('game/settings', data.message)
          break
        case 'gameUpdate':
          store.dispatch('game/update', data.message)
          break
        case 'gamePlayerDead':
          store.dispatch('game/dead', data.message)
          break
        default:
          break
      }
    }
  }
}

export function send (message) {
  // console.log('[WS] send', message)
  connection.send(JSON.stringify(message))
}
