import axios from 'axios';
import _ from 'lodash';

export default {
  namespaced: true,
  state: {
    list: [],
    fields: [],
    filter: {
      by: undefined,
      value: undefined,
    },
  },
  mutations: {
    updateSearch(state, data) {
      state.list = [];
      state.fields = [];
      state.list = data;
      data.forEach((item) => {
        state.fields.push(item.property);
      });
      state.fields.push('UserName');
      state.fields.push('Type');
      state.fields.push('Date');
      state.fields.push('Time');
      state.fields = state.fields.filter((x, i, a) => a.indexOf(x) === i);
    },
    onClearFilter(state) {
      state.filter = {
        by: undefined,
        value: undefined,
      };
    },
  },
  getters: {
    filterList: (state) => {
      let lst = state.list;
      const { filter } = state;
      if (filter) {
        if (filter.by) {
          if (filter.by === 'UserName') {
            lst = _.filter(lst, x => x.userName.toUpperCase().includes(filter.value.toUpperCase()));
          } else if (filter.by === 'Type') {
            lst = _.filter(lst, x => x.type.toUpperCase().includes(filter.value.toUpperCase()));
          } else if (filter.by === 'Date') {
            lst = _.filter(lst, x => x.date.toUpperCase().includes(filter.value.toUpperCase()));
          } else if (filter.by === 'Time') {
            lst = _.filter(lst, x => x.time.toUpperCase().includes(filter.value.toUpperCase()));
          } else {
            lst = _.filter(lst, x => x.property === filter.by);
            if (filter.value) {
              lst = _.filter(lst, x => x.value.toUpperCase().includes(filter.value.toUpperCase()));
            }
          }
        } else if (filter.value) {
          lst = _.filter(
            lst,
            x => x.value.toUpperCase().includes(filter.value.toUpperCase())
              || x.userName.toUpperCase().includes(filter.value.toUpperCase())
              || x.type.toUpperCase().includes(filter.value.toUpperCase()),
          );
        }
      }
      return lst;
    },
  },
  actions: {
    getPropertySearchLogs({ commit }) {
      axios
        .get('/api/searchLog')
        .then(result => commit('updateSearch', result.data))
        .catch(console.error);
    },
    clearFilter({ commit }) {
      commit('onClearFilter');
    },
  },
};
