// 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')

// setTimeout(send({ type: 'alive' }), 5000)

export default function createSignalPlugin () {
  return store => {
    connection.onopen = function () {
      console.log('[WS] connected')
      store.dispatch('app/signalConnected')
    }

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

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

      var data = JSON.parse(message.data)

      switch (data.type) {
        case 'offer':
          console.log('offer from ' + data.name)
          store.dispatch('rtc/offer', { offer: data.data, senderName: data.name })
          break

        case 'answer':
          console.log('answer from ' + data.name)
          store.dispatch('rtc/answer', { answer: data.data, senderName: data.name })
          break

        case 'candidate':
          store.dispatch('rtc/candidate', { candidate: data.data, senderName: data.name })
          break

        case 'leave':
          store.dispatch('rtc/leave')
          break

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

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

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

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

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

        default:
          break
      }
    }
  }
}

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