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

Vue.use(Vuex)

export const store = new Vuex.Store({
  // strict: true,  // not in production

  state: {
    myCatalogs: [],
    publicCatalogs: [],
    loadingMyCatalogs: true,
    loadingPublicCatalogs: true,
    selectedCatalog: null,
  },

  getters: {
    findCatalog: (state) => (id) => {
      let cat = state.myCatalogs.find(c => c.id === id)
      if (cat !== undefined) {
        return cat
      } else {
        return state.publicCatalogs.find(c => c.id === id)
      }
    },
  },

  mutations: {
    setMyCatalogs(state, cats) {
      state.myCatalogs = cats
    },
    setLoadingMyCatalogs(state, value) {
      state.loadingMyCatalogs = value
    },
    setPublicCatalogs(state, cats) {
      state.publicCatalogs = cats
    },
    setLoadingPublicCatalogs(state, value) {
      state.loadingPublicCatalogs = value
    },
    setSelectedCatalog(state, cat) {
      state.selectedCatalog = cat
    },
  },

  actions: {
    async loadMyCatalogs({ commit, state }) {
      try {
        commit('setLoadingMyCatalogs', true)
        const response = await axios.get('/api/v1/catalogs/mine')
        if ('catalogs' in response.data) {
          // console.log('recieved catalogs:', response.data.catalogs)
          commit('setMyCatalogs', response.data.catalogs)
          if (response.data.catalogs.length > 0) {
            if (state.selectedCatalog == null) {
              commit('setSelectedCatalog', response.data.catalogs[0])
            } else {
              let cat = response.data.catalogs.find(c => c.id === state.selectedCatalog.id)
              if (cat) {
                commit('setSelectedCatalog', cat)
              } // otherwise might be a public catalog
            }
          }
        } else {
          // console.log('no catalogs')
          commit('setMyCatalogs', [])
        }
        commit('setLoadingMyCatalogs', false)
      } catch (error) {
        // TODO set loading error property
        console.error(error)
        commit('setMyCatalogs', [])
        commit('setLoadingMyCatalogs', false)
      }
    },

    async loadPublicCatalogs({ commit }) {
      try {
        commit('setLoadingPublicCatalogs', true)
        const response = await axios.get('/api/v1/catalogs/public')
        if ('catalogs' in response.data) {
          // console.log('recieved catalogs:', response.data.catalogs)
          commit('setPublicCatalogs', response.data.catalogs)
        } else {
          // console.log('no catalogs')
          commit('setPublicCatalogs', [])
        }
        commit('setLoadingPublicCatalogs', false)
      } catch (error) {
        // TODO set loading error property
        console.error(error)
        commit('setPublicCatalogs', [])
        commit('setLoadingPublicCatalogs', false)
      }
    },

    setSelectedCatalog(context, id) {
      let cat = context.getters.findCatalog(id)
      context.commit('setSelectedCatalog', cat)
    },
  },
})
