import pinia from './init'
import { useAppStore } from './index'
import { exists_file, read_config_file, toPage } from '../utils/tools'
import { isArrIndex, isNullES } from 'js-fast-way'

const store = useAppStore(pinia)

//获取项目信息
export const getProjectInfo = async () => {
    //获取数据存储路径
    const { dataPath } = read_config_file()
    store.setDataPath(dataPath)
    if (!exists_file(dataPath)) {
        toPage({
            page: '/init',
            query: { source: '' },
        })
        return { code: 300 }
    }
    //获取项目数据
    let projectPath = dataPath + '/project.json'
    //项目数据不存在
    let newData = { current: { key: '', name: '' }, data: [] }
    if (!exists_file(projectPath)) {
        window.api.fs.writeFileSync(projectPath, JSON.stringify(newData), 'utf-8')
        store.setProjectInfo({})
        store.setProjectData([])
        return { code: 300, ...newData }
    }
    //读取项目数据
    const content = window.api.fs.readFileSync(projectPath, 'utf-8')
    const { current, data } = JSON.parse(content)
    if (data.length <= 0) {
        store.setProjectInfo({})
        store.setProjectData([])
        return { code: 300, ...newData }
    }
    //检测项目数据是否真实存在
    for (let i = 0; i < data.length; i++) {
        let projectDataPath = `${dataPath}/${data[i].key}/data`
        if (!exists_file(projectDataPath)) {
            data.splice(i, 1)
        }
    }
    //再次检查项目数据
    if (data.length <= 0) {
        window.api.fs.writeFileSync(projectPath, JSON.stringify(newData), 'utf-8')
        store.setProjectInfo({})
        store.setProjectData([])
        return { code: 300, ...newData }
    }
    //判断默认项目是否存在
    let projectInfo = current
    if (isNullES(current.key) || !isArrIndex(data, 'key', current.key)) {
        projectInfo = data[0]
    }
    //设置项目信息
    store.setProjectInfo(projectInfo)
    store.setProjectData(data)
    window.api.fs.writeFileSync(projectPath, JSON.stringify({
        current: projectInfo, data: data,
    }), 'utf-8')
    return { code: 200, current: projectInfo, data: data }
}
