// const connection = new WebSocket('ws://localhost:8181/socket')
// const connection = new WebSocket('wss://echo.websocket.org')
const connection = new WebSocket('wss://voozik.gltronic.ovh/socket')

var alive = null

export default function createSignalPlugin () {
  return store => {
    connection.onopen = function () {
      console.log('[WS] connected')
      store.dispatch('app/signalConnected')
      alive = setTimeout(send({ type: 'alive' }), 5000)
    }

    connection.onclose = function () {
      clearTimeout(alive)
    }

    connection.onerror = function (error) {
      console.log('[WS] error ' + error.type)
      clearTimeout(alive)
      store.dispatch('app/signalError', error.type)
    }

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

      var data = JSON.parse(message.data)

      switch (data.type) {
        case 'leave':
          break

        case 'login':
          store.dispatch('app/login', data.message)
          break

        case 'serverInfos':
          store.dispatch('app/serverStatus', data.message)
          break

        case 'roomCreate':
          store.dispatch('room/createRoom', data.message)
          break

        case 'roomConnect':
          store.dispatch('app/connectRoom', data.message)
          break

        case 'error':
          store.dispatch('app/error', data.message)
          break

        case 'roomStatus':
          if (store.state.room.admin) store.dispatch('room/setRoomStatus', data.message)
          break

        case 'roomSettings':
          if (!store.state.room.admin) store.dispatch('room/setRoomSettings', data.message)
          break

        case 'roomVote':
          store.dispatch('room/vote', { link: data.message.link, linkID: data.message.linkID, isPositive: data.message.isPositive, voterName: data.message.voterName })
          break

        case 'roomUserCommand':
          if (store.state.room.roomSettings.userControl) store.dispatch('room/setUserCommand', data.message)
          break

        case 'roomUserKick':
          store.dispatch('room/leave', data.message)
          break

        default:
          break
      }
    }
  }
}

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