import { ToastProgrammatic as Toast } from 'buefy'

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

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

    connection.onclose = function () {
      console.log('[WS] closed')
      store.dispatch('game/socketConnected', false)
    }

    connection.onerror = function (error) {
      console.log('[WS] error ' + error.message)
      Toast.open('Connection problem. Retrying in 10s...')
      setTimeout(function () {
        location.reload()
      }, 10000)
    }

    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.player)
          break
        case 'gameSettings':
          store.dispatch('game/settings', data.gameSettings)
          break
        case 'gameUpdate':
          store.dispatch('game/update', data)
          break
        case 'gamePlayerDead':
          store.dispatch('game/dead', data.player)
          break
        case 'gamePlayerSpawn':
          store.dispatch('game/spawn', data.player)
          break
        default:
          break
      }
    }
  }
}

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