import {ManipulatorInterfaceType} from '../types'
import fs from 'fs-extra'
import path from 'path'
import utils from '../utils'

type ReaderFileConfig = {
    name: string //name without ext
    ext?: string //name without ext
    path: string //path file locate folder parent
    encoding?: BufferEncoding //result file code (default urf8)
}
type ReaderFolderOutConfig = {
    path: string //path folder locate parent
    name: string //name folder
}

export type ReturnReadFileType = { readed: boolean, result: string }
export type ReturnReadFolderType = { readed: boolean, result: string[] }

type FixFuncReturnType = (x?: any) => Promise<ReturnReadFileType | ReturnReadFolderType>

export abstract class ManipulatorReaderInterfaceType {
    folder: FixFuncReturnType | undefined
    file: FixFuncReturnType | undefined
}

class Reader implements ManipulatorReaderInterfaceType {
    async file(config: ReaderFileConfig): Promise<ReturnReadFileType> {
        try {
            //file names
            const startFullName = utils.getNameByConfig(config)
            //file pathes
            const startFullPath = path.resolve(config.path, startFullName)
            //operations
            const result = await utils.readFile(startFullPath, config?.encoding)
            return {result, readed: true}
        } catch (e) {
            console.log(this.constructor.name, `[${this.file.name}]`, config.name, e)
            return {result: '', readed: false}
        }
    }

    async folder(config: ReaderFolderOutConfig): Promise<ReturnReadFolderType> {
        try {
            //file names
            const startFullName = `${config.name}`
            //file pathes
            const startFullPath = path.resolve(config.path, startFullName)
            //operations
            const files = await fs.readdir(startFullPath)
            return {readed: true, result: files}
        } catch (e) {
            console.log(this.constructor.name, `[${this.folder.name}]`, config.name, e)
            return {readed: false, result: []}
        }
    }
}

export default new Reader()
