import _JSON$stringify from "@babel/runtime-corejs2/core-js/json/stringify";
import _Object$getPrototypeOf from "@babel/runtime-corejs2/core-js/object/get-prototype-of";
import _Object$defineProperties from "@babel/runtime-corejs2/core-js/object/define-properties";
import "core-js/modules/web.dom.iterable";

// 定义搜索历史记录 通用类
const searchHistory = function (length, store) {
  const list = JSON.parse(localStorage.getItem(store)) || [];
  const ids = [];

  if (list.length) {
    list.forEach(item => ids.push(item.search_word));
  }

  _Object$defineProperties(list, {
    pop: {
      value: () => {
        _Object$getPrototypeOf(list).pop.call(list);

        ids.pop();
      }
    },
    splice: {
      value: (...args) => {
        _Object$getPrototypeOf(list).splice.call(list, ...args);

        ids.splice(...args);
      }
    },
    unshift: {
      value: val => {
        _Object$getPrototypeOf(list).unshift.call(list, val);

        ids.unshift(val.search_word);
      }
    }
  });

  const history = {
    list,
    ids,

    get limit() {
      return length;
    },

    get length() {
      return this.list.length;
    },

    get(searchWord) {
      const idx = this.ids.indexOf(searchWord);
      if (idx === -1) return {};
      return this.list[idx];
    },

    append(val, save = true) {
      // this.remove(val, false);
      this.list.unshift(val);

      if (this.length > this.limit) {
        this.expel(false);
      }

      save && this.save();
    },

    expel(save) {
      this.list.pop();
      save && this.save();
    },

    remove(val, save = true) {
      const idx = this.ids.indexOf(val.search_word);
      if (idx === -1) return; // this.list.splice(idx, 1);

      this.list = this.list.filter(item => item.search_word !== val.search_word);
      save && this.save();
    },

    save() {
      localStorage.setItem(store, _JSON$stringify(this.list));
    },

    clear() {
      this.list = [];
      this.ids = [];
      localStorage.removeItem(store);
    }

  };
  return history;
};

export default searchHistory;