import glob from "fast-glob"
import path from "path"
import _ from "lodash"
import fs from "fs-extra"
import {getOutput, getPkgs, rootDir} from "@princess-ui/share"

export async function getComponents() {
    const res = await glob("components/*/index.ts", { cwd: path.resolve(__dirname, "..") })
    const components = res.map(v => {
        const name = path.parse(v.replace("components/", "")).dir
        return name
    })
    return components
}

export async function generateComponents(components?: string[]) {
    // const componetnsStr: string[] = [`// 该文件为自动生成,请勿修改!!!`]
    const newComp: string[] = []
    const typeArray: string[] = []
    let typeStr = `declare module 'vue' {
    export interface GlobalComponents {
        __placeholder__
    }
}
export { }`
    if (!components) {
        components = await getComponents()
    }
    components.forEach(name => {
        const n = "Ps" + _.upperFirst(_.kebabCase(name))
        // componetnsStr.push(`import ${n} from "./${name}"`)
        newComp.push(n)
        typeArray.push(n + `: typeof import('princess-ui')['${n}']`)
    })
    // componetnsStr.push(`export { \n  ${newComp.join(",\n  ")} \n}`)
    typeStr = typeStr.replace("__placeholder__", typeArray.join(',\n        '))
    await fs.writeFile(getOutput("components.d.ts"), typeStr)
    // await fs.writeFile(getPkgs("components/components.ts"), componetnsStr.join("\n"))
}