import { DialogProgrammatic as Dialog } from 'buefy'
import router from '@/router/index'

const state = {
  signalServerConnected: false,
  loginSuccess: null,
  error: null,
  serverStatus: {}
}

const getters = {
  displayError: state => state.error,
  displayUserList: state => state.userList,
  displayLoginStatus: state => state.loginSuccess,
  displayServerStatus: state => state.signalServerConnected
}

const actions = {
  signalConnected ({ commit }) {
    commit('SIGNAL_SUCCESS')
  },
  signalError ({ commit }, error) {
    commit('SIGNAL_ERROR', error)
  },
  login ({ commit }, success) {
    // le JSON parser veut pas voir le boolean
    if (success === 'true') commit('LOGIN_SUCCESS')
    else commit('LOGIN_ERROR')
  },
  resetLogin ({ commit }) {
    commit('LOGIN_RESET')
  },
  serverStatus ({ commit }, serverStatus) {
    commit('SET_SERVERSTATUS', serverStatus)
  },
  createRoom ({ commit, dispatch }, code) {
    commit('CREATE_ROOM')
    dispatch('room/setRoomCode', code, { root: true })
    dispatch('room/setAdmin', null, { root: true })
  },
  connectRoom ({ commit, dispatch }, name) {
    commit('CONNECT_ROOM')
    dispatch('rtc/makeOffer', name, { root: true })
  },
  error ({ commit }, error) {
    commit('ERROR', error)
  }
}

const mutations = {
  SIGNAL_SUCCESS (state) {
    state.signalServerConnected = true
  },
  SIGNAL_ERROR (state, error) {
    state.signalServerConnected = false
    state.error = error
  },
  LOGIN_SUCCESS (state) {
    state.loginSuccess = true
  },
  LOGIN_ERROR (state) {
    state.loginSuccess = false
  },
  LOGIN_RESET (state) {
    state.loginSuccess = null
  },
  SET_SERVERSTATUS (state, serverStatus) {
    state.serverStatus = serverStatus
  },
  CREATE_ROOM (state) {
    router.push({ name: 'Room' })
  },
  CONNECT_ROOM (state) {
    router.push({ name: 'Room' })
  },
  ERROR (state, error) {
    state.error = error
    Dialog.alert(error)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
