import { ServiceContent } from 'types/ServiceContent'
import loadAndPrepareMarkdown from './use-markdown-parser'
import fs from 'fs'
import path from 'path'

const useContent = () => {
    const contents: ServiceContent[] = readMarkdownFilesFromResources()

    const contentByServiceName = (selectedServiceName: string) => {
        if (contents.length > 0) {
            // try to read entry
            console.log('contents array initialized', contents.length)
            // return
        }
        const content: ServiceContent = getContentByServiceName(selectedServiceName)
        return content
    }

    return {
        contents,
        contentByServiceName,
    }
}

function getContentByServiceName(selectedServiceName: string) {
    return prepareServiceContent(selectedServiceName)
}

function prepareServiceContent(selectedServiceName: string) {
    const content: ServiceContent = loadAndPrepareMarkdown(selectedServiceName)
    return content
}

function readMarkdownFilesFromResources(): ServiceContent[] {
    const resourcesDirectory = path.join(process.cwd(), 'content', 'resources')

    // read all folder in 'resources'-directory
    const serviceDirectories: string[] = fs.readdirSync(resourcesDirectory, { withFileTypes: true })
        .filter((serviceDirectory: fs.Dirent) => serviceDirectory.isDirectory())
        .map((serviceDirectory: fs.Dirent) => serviceDirectory.name)

    return serviceDirectories.map((serviceDirectory: string) => {
        return loadAndPrepareMarkdown(serviceDirectory)
    })
}

export default useContent