import { defineStore } from 'pinia';
import { useApiStore } from './api.js';
import { ref, computed } from 'vue';

export const useProjectsStore = defineStore('projects', () => {
  const isProjectsLoading = ref(true);
  const projects = ref(null);

  const currentProjects = computed(() => {
    return projects.value
      .filter((project) => project.status === 'listed')
      .sort((a, b) => new Date(b.modified) - new Date(a.modified));
  });

  const draftProjects = computed(() => {
    return projects.value
      .filter((project) => project.status === 'draft')
      .sort((a, b) => new Date(b.modified) - new Date(a.modified));
  });

  const archivedProjects = computed(() => {
    return projects.value
      .filter((project) => project.status === 'unlisted')
      .sort((a, b) => new Date(b.modified) - new Date(a.modified));
  });

  const api = useApiStore();
  api.fetchData('projects').then((json) => {
    // setTimeout(() => {
    isProjectsLoading.value = false;
    projects.value = json.page.children;
    // }, 3000);
  });

  // Functions
  function getProjectByUuid(uuid) {
    const project = projects.value.find((project) => project.uuid === uuid);
    return project;
  }

  return {
    projects,
    currentProjects,
    archivedProjects,
    draftProjects,
    getProjectByUuid,
    isProjectsLoading,
  };
});
