import Vue from 'vue'
import Vuex from 'vuex'
import app from '../../main' // import the instance
import { AxiosResponse } from 'axios'
import checkResponse from '@/utils/checkResponse'
import parserSlug from '@/utils/parserSlug'
import moment from 'moment'

Vue.use(Vuex)

const state = {
  appName: '',
  backUrl: '',
  csrfToken: '',
  menuItems: [],
  isNotificationsVisible: false,
  notifications: [],
  menu: [],
  settings: {},
  alertMessage: {},
  acceptAlert: {},
  isModalFeedbackVisible: false,
  isModalImportVisible: false
}

const mutations = {
  SET_BACK_URL (state, payload) {
    state.backUrl = payload
  },
  SET_DATA (state, payload) {
    const token = document.head.querySelector('meta[name="csrf-token"]')

    if (token) {
      payload.csrfToken = (token).content
    }

    Object.assign(state, { ...payload })
  },
  ADD_NOTIFICATION (state, payload) {
    state.notifications.unshift(payload)
  },
  DELETE_NOTIFICATION (state, payload) {
    const idx = state.notifications.findIndex(u => u.id === payload.id)
    if (idx >= 0) {
      Vue.delete(state.notifications, idx, payload)
    }
  },
  DELETE_NOTIFICATIONS (state, payload) {
    state.notifications = []
  },
  SET_MENU (state, payload) {
    state.menu = payload
  },
  SET_ALERT_MESSAGE (state, payload) {
    state.alertMessage = payload
  },
  SET_ACCEPT_ALERT (state, payload) {
    state.acceptAlert = payload
  },
  SET_MODAL_FEEDBACK_VISIBLE (state, payload) {
    state.isModalFeedbackVisible = payload
  },
  SET_MODAL_IMPORT_VISIBLE (state, payload) {
    state.isModalImportVisible = payload
  },
  TOGGLE_NOTIFICATIONS (state) {
    state.isNotificationsVisible = !state.isNotificationsVisible
  },
  CLOSE_NOTIFICATIONS (state) {
    state.isNotificationsVisible = false
  }
}

const actions = {
  setBackUrl ({ commit }, payload) {
    commit('SET_BACK_URL', payload)
  },
  async loadData ({ commit }) {
    let response = AxiosResponse

    try {
      response = await Vue.axios.get('vue')
    } catch (error) {
      alert(Vue.i18n.translate('errors.generic_error', null))
      window.location.reload()
      return
    }

    const { status, data } = response

    if (status === 200 && !data.errors) {
      commit('SET_DATA', data)
    }
  },
  addNotification ({ commit }, payload) {
    let notification = {
      id: payload.id,
      created_at: moment(),
      data: payload.data
    }
    Notification.requestPermission(permission => {
      let notification = new Notification(app.$t(payload.data.title), {
        body: `${payload.data.user} ${app.$t(payload.data.message)}`, // content for the alert
        icon: `${Vue.axios.defaults.baseURL}/img/icons/apple-touch-icon-180x180.png` // optional image url
      })

      notification.onclick = () => {
        app.$router.push({ path: payload.data.path })
      }
    })
    commit('ADD_NOTIFICATION', notification)
  },
  async clickNotification ({ commit }, payload) {
    try {
      const response = await Vue.axios.delete(`users/${app.$auth.user().id}/notifications/${payload.id}`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        let route = app.$router.resolve({ path: payload.data.path }, true)
        window.open(route.href, '_blank')
        commit('DELETE_NOTIFICATION', payload)
      }
    } catch (e) {
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    }
  },
  async markAllNotifications ({ commit }, payload) {
    try {
      const response = await Vue.axios.delete(`users/${app.$auth.user().id}/notifications`)
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message }, { root: true })
      } else {
        commit('DELETE_NOTIFICATIONS', payload)
      }
    } catch (e) {
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' }, { root: true })
    }
  },
  setMenu ({ commit }, payload) {
    commit('SET_MENU', payload)
  },
  setAlertMessage ({ commit }, payload) {
    commit('SET_ALERT_MESSAGE', payload)
  },
  setAcceptAlert ({ commit }, payload) {
    commit('SET_ACCEPT_ALERT', payload)
  },
  setModalFeedbackVisible ({ commit }, payload) {
    commit('SET_MODAL_FEEDBACK_VISIBLE', payload)
  },
  setModalImportVisible ({ commit }, payload) {
    commit('SET_MODAL_IMPORT_VISIBLE', payload)
  },
  setNotificationsVisible ({ commit, state }) {
    commit('TOGGLE_NOTIFICATIONS')
  },
  closeNotifications ({ commit, state }) {
    commit('CLOSE_NOTIFICATIONS')
  },
  async sendFeedback ({ commit }, payload) {
    app.$Progress.start()
    try {
      const response = await Vue.axios.post('https://api.crm.controlla.com.mx/feedback')
      const checkErrors = checkResponse(response)

      if (checkErrors) {
        app.$Progress.fail()
        commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: checkErrors.message })
      } else {
        commit('SET_MODAL_FEEDBACK_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.feedback', text: 'front.feedback_successfully', icon: 'checkmark-circle-outline' })
      }
    } catch (e) {
      app.$Progress.fail()
      commit('SET_ALERT_MESSAGE', { color: 'danger', title: 'errors.connection_error', text: 'errors.generic_error' })
    } finally {
      app.$Progress.finish()
    }
  },
  async downloadTemplate ({ commit }, payload) {
    app.$Progress.start()
    let url = parserSlug(payload.model)
    try {
      window.open(`${Vue.axios.defaults.baseURL}/${url}/template`)
    } catch (error) {
      app.$Progress.fail()
    } finally {
      app.$Progress.finish()
    }
  },
  async importData ({ commit }, payload) {
    let url = parserSlug(payload.model)
    let formData = new FormData()
    formData.append('importFile', payload.file)

    app.$Progress.start()

    try {
      const response = await Vue.axios.post(`${url}/import`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      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_MODAL_IMPORT_VISIBLE', false)
        commit('SET_ACCEPT_ALERT', { color: 'success', title: 'strings.products', 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()
    }
  }
}

const getters = {
  notifications: state => state.notifications,
  isNotificationsVisible: state => state.isNotificationsVisible,
  csrfToken: state => state.csrfToken,
  menu: state => state.menu,
  menuItems: state => state.menuItems,
  backUrl: state => state.backUrl,
  alertMessage: state => state.alertMessage,
  acceptAlert: state => state.acceptAlert,
  isModalFeedbackVisible: state => state.isModalFeedbackVisible,
  isModalImportVisible: state => state.isModalImportVisible
}

export default {
  state,
  mutations,
  actions,
  getters
}
