/*
This file is part of ArciveList.

# SPDX-FileCopyrightText: 2021 Hangar.org
# SPDX-License-Identifier: AGPL-3.0-or-later
*/

import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'underscore';


Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    search_text: "",
    sites: [],
    filtered_sites: [],
    page_count: 1,
  },
  mutations: {
    setSearchText(state, text) {
      state.search_text = text
    },
    setSites(state, payload) {
      state.sites = _.sortBy(payload.sites, payload.column_name)
    },
    incrementPageCount(state) {
      state.page_count = state.page_count +1
    },
    setFilteredSites(state, filtered_site_ids) {
      console.log('filtered_site_ids')
      console.log(filtered_site_ids)
      var sites = []
      for (const [site_id, weight] of Object.entries(filtered_site_ids)) {
        var site = state.sites.find(x => x.id == site_id)
        if (site) {
          console.log('push')
          sites.push(site)
        }
      }
      state.filtered_sites = sites
      state.page_count = 1
    },
    setColumnOrder(state, payload) {
      state.sites = _.sortBy(state.sites, payload.column_name)
      state.filtered_sites = _.sortBy(state.filtered_sites, payload.column_name)
      if (payload.order == 'desc') {
        state.sites.reverse()
        state.filtered_sites.reverse()
      }
    },
  },
  getters: {
    getSitesForDisplay: state => {
      if (state.search_text === "") {
        return state.sites
      }
      return state.filtered_sites
    },
    getPageCount: state => {
      return state.page_count
    },
    searchLocalSiteData: state => {
      var result = {}
      if (state.search_text==="") {
        return result
      }
      for (let site in state.sites) {
        var weight = 0
        var found = state.sites[site].summary.toLowerCase().search(state.search_text.toLowerCase())
        if (found != -1) {
          weight = weight +1
        }
        var found = state.sites[site].collection.toLowerCase().search(state.search_text.toLowerCase())
        if (found != -1) {
          weight = weight +1
        }
        var found = state.sites[site].currator.toLowerCase().search(state.search_text.toLowerCase())
        if (found != -1) {
          weight = weight +1
        }
        if (weight > 0) {
          var id = state.sites[site].id
          result[id] = weight
        }
      }
      console.log('load search')
      console.log(result)
      return result
    },
  }
})

export default store