import {defineStore} from 'pinia'
import majorManager from "app/src/api/major/major";
import {ref} from "vue";

export const useMajorsStore =
  defineStore('majors', () => {

      const majors = ref()
      const majorNames = ref({})

      let loadLock = undefined

      async function loadMajors() {
        if (majors.value && majors.value.length) {
          return majors
        }

        return await refreshMajors()
      }

      async function refreshMajors() {
        if (!loadLock) {
          loadLock = {}
          const newMajors = await majorManager.list()
          for (const major  of newMajors) {
            majorNames.value[major.id] = major.name
          }
          majors.value = newMajors
          loadLock = undefined
        }

        return majors
      }

      function majorNameFromId(id) {
        if (majors.value) {
          for (const major of majors.value) {
            if (major.id === id) {
              return major.name
            }
          }
        }

        // 没找到，刷新一下
        ;(async () => refreshMajors())()

        return ''
      }

      return {majors, majorNames, loadMajors, refreshMajors, majorNameFromId}
    }
  )
