// useViewsStore.js
import { defineStore } from 'pinia';

export const useViewsStore = defineStore('views', {
  state: () => ({
    visitedViews: [],
    cachedViews: []
  }),

  actions: {
    addView(view) {
      this.addVisitedView(view);
      this.addCachedView(view);
    },
    addVisitedView(view) {
      if (this.visitedViews.some(v => v.path === view.path)) return;
      this.visitedViews.push({
        ...view,
        title: view.meta.title || 'no-name'
      });
    },
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return;
      if (!view.meta.noCache) {
        this.cachedViews.push(view.name);
      }
    },

    delView(view) {
      this.delVisitedView(view);
      this.delCachedView(view);
    },
    delVisitedView(view) {
      const index = this.visitedViews.findIndex(v => v.path === view.path);
      if (index > -1) {
        this.visitedViews.splice(index, 1);
      }
    },
    delCachedView(view) {
      const index = this.cachedViews.indexOf(view.name);
      if (index > -1) {
        this.cachedViews.splice(index, 1);
      }
    },

    delOthersViews(view) {
      this.delOthersVisitedViews(view);
      this.delOthersCachedViews(view);
    },
    delOthersVisitedViews(view) {
      this.visitedViews = this.visitedViews.filter(v => v.meta.affix || v.path === view.path);
    },
    delOthersCachedViews(view) {
      const index = this.cachedViews.indexOf(view.name);
      if (index > -1) {
        this.cachedViews = this.cachedViews.slice(index, index + 1);
      } else {
        this.cachedViews = [];
      }
    },

    delAllViews() {
      this.delAllVisitedViews();
      this.delAllCachedViews();
    },
    delAllVisitedViews() {
      const affixTags = this.visitedViews.filter(tag => tag.meta.affix);
      this.visitedViews = affixTags;
    },
    delAllCachedViews() {
      this.cachedViews = [];
    },

    updateVisitedView(view) {
      for (let i = 0; i < this.visitedViews.length; i++) {
        if (this.visitedViews[i].path === view.path) {
          this.visitedViews[i] = { ...this.visitedViews[i], ...view };
          break;
        }
      }
    }
  },
  persist: true
});