import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		status: '',
		token: localStorage.getItem('token') || '',
        user: {},
        pagenum: '1',
        numpages: '-1'
	},
	mutations: {
		auth_request(state) {
			state.status = 'loading'
		},
		auth_success(state, token, user) {
			state.status = 'success'
			state.token = token
			state.user = user
		},
		auth_error(state, err) {
			state.status = err
		},
		logout(state) {
			state.status = ''
			state.token = ''
        },
        updatePageNum(state, num){
            console.log(num)
            state.pagenum = num
        },
        updatePageCount(state, pagecount){
            console.log(pagecount)
            state.numpages = pagecount
        }
	},
	actions: {
		login({
			commit
		}, user) {
			return new Promise((resolve, reject) => {
				commit('auth_request')
				axios({
						url: 'https://grasperapi.azurewebsites.net/api/v1/Users/authenticate',
						data: user,
						method: 'POST'
					})
					.then(resp => {
						const token = resp.data.token
						const user = resp.data.user
						localStorage.setItem('token', token)
                        // Add the following line:
						axios.defaults.headers.common['Authorization'] = token
						commit('auth_success', token, user)
						resolve(resp)
					})
					.catch(err => {
                        commit('auth_error', err)
						localStorage.removeItem('token')
						reject(err)
					})
			})
		},
		register({
			commit
		}, user) {
			return new Promise((resolve, reject) => {
				commit('auth_request')
				axios({
						url: 'https://grasperapi.azurewebsites.net/api/v1/Users/register',
						data: user,
						method: 'POST'
					})
					.then(resp => {
						const token = resp.data.token
						const user = resp.data.user
						localStorage.setItem('token', token)
						// Add the following line:
						axios.defaults.headers.common['Authorization'] = token
						commit('auth_success', token, user)
						resolve(resp)
					})
					.catch(err => {
						commit('auth_error', err)
						localStorage.removeItem('token')
						reject(err)
					})
			})
		},
		logout({
			commit
		}) {
			return new Promise((resolve, reject) => {
				commit('logout')
				localStorage.removeItem('token')
				delete axios.defaults.headers.common['Authorization']
				resolve()
			})
		}
	},
	getters: {
		isLoggedIn: state => !!state.token,
		authStatus: state => state.status,
	}
})