import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import app from '../../main' // import the instance
import checkResponse from '@/utils/checkResponse'
import parserFilters from '@/utils/parserFilters'
import parserSlug from '@/utils/parserSlug'

Vue.use(Vuex)

const state = {
  users: [],
  pagination: {
    currentPage: 1,
    perPage: 5,
    totalUsers: 0,
    totalPages: 0
  },
  usersCatalog: {},
  filterParams: '',
  isModalVisible: false
}

const mutations = {
  SET_USERS (state, payload) {
    state.users = payload.data

    state.pagination = {
      currentPage: payload.current_page,
      perPage: payload.per_page,
      totalUsers: payload.total,
      totalPages: payload.last_page
    }
  },
  ADD_USER (state, payload) {
    state.users.unshift(payload)
  },
  UPDATE_USER (state, payload) {
    const idx = state.users.findIndex(u => u.id === payload.id)

    if (idx >= 0) {
      Vue.set(state.users, idx, payload)
    }
  },
  DELETE_USER (state, payload) {
    const idx = state.users.findIndex(u => u.id === payload.id)

    if (idx >= 0) {
      Vue.delete(state.users, idx)
    }
  },
  DELETE_USERS (state, payload) {
    for (let id of payload.ids) {
      const idx = state.users.findIndex(u => u.id === id)

      if (idx >= 0) {
        Vue.delete(state.users, idx)
      }
    }
  },
  SET_MODAL_VISIBLE (state, payload) {
    state.isModalVisible = payload
  },
  SET_FILTER_PARAMS (state, payload) {
    state.filterParams = payload
  },
  SET_CATALOG (state, { object, payload }) {
    state.usersCatalog[object] = payload.data
  }
}

const actions = {
  async loadUsers ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.get(`users?page=${payload.page}${state.filterParams}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('SET_USERS', response.data)
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async addUser ({ commit }, payload) {
    const user = {
      name: payload.name,
      email: payload.email,
      password: payload.password,
      role: payload.role
    }

    app.$Progress.start()

    try {
      const response = await axios.post('users', user)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('ADD_USER', response.data)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.users', text: 'front.added_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async editUser ({ commit }, payload) {
    const user = {
      name: payload.name,
      email: payload.email,
      password: payload.password,
      role: payload.role
    }

    app.$Progress.start()

    try {
      const response = await axios.put(`users/${payload.id}`, user)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('UPDATE_USER', response.data)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.users', text: 'front.updated_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async deleteUser ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.delete(`users/${payload.id}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('DELETE_USER', payload)
        commit('SET_MODAL_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.users', text: 'front.deleted_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async deleteUsers ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.delete(`users/delete`, { params: { ids: payload.ids } })
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('DELETE_USERS', payload)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.users', text: 'front.deleted_successfully', icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  async actionUser ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await axios.put(`users/${payload.id}/${payload.action}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('UPDATE_USER', response.data)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.users', text: `users.${payload.action}`, icon: 'checkmark-circle-outline' }, { root: true })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  printReport ({ commit }, payload) {
    app.$Progress.start()
    try {
      window.open(axios.defaults.baseURL + '/users/export?' + state.filterParams)
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  applyFilter ({ commit }, payload) {
    const filter = parserFilters(payload)
    commit('SET_FILTER_PARAMS', filter)
  },
  clearFilter ({ commit }, payload) {
    const filter = ''
    commit('SET_FILTER_PARAMS', filter)
  },
  async loadCatalog ({ commit }, payload) {
    let url = parserSlug(payload.url)
    app.$Progress.start()
    try {
      const response = await axios.get(`${url}${payload.filter}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('SET_CATALOG', { object: payload.url, payload: response.data })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    } finally {
      app.$Progress.finish()
    }
  },
  setModalVisible ({ commit }, payload) {
    commit('SET_MODAL_VISIBLE', payload)
  }
}

const getters = {
  users: state => state.users,
  usersCatalog: state => state.usersCatalog,
  pagination: state => state.pagination,
  isModalVisible: state => state.isModalVisible,
  filterParams: state => state.filterParams
}

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