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

type CreatorFileConfig = {
    path: string //path without name
    name: string //name without ext
    ext?: string //name without ext
    content?: string //default empty string (inside)
    replaceExisting?: boolean //replace if there is exist the same file ? (default false)
    encoding?: BufferEncoding //default "utf8"
}
type CreatorFolderOutConfig = {
    path: string //path without name
    name: string //name folder
    replaceExisting?: boolean //replace if there is exist the same file (default false)
}

class Creator implements ManipulatorInterfaceType {
    async file(config: CreatorFileConfig) {
        try {
            //file names
            const startFullName = utils.getNameByConfig(config)
            //file pathes
            const startFullPath = path.resolve(config.path, startFullName)
            //operations
            const isExist = await utils.checkExist(startFullPath)
            const canBeWrited = !isExist || (isExist && config?.replaceExisting)
            if (canBeWrited) {
                await fs.writeFile(startFullPath, config?.content || '', {encoding: config?.encoding || 'utf8'})
                return true
            } else {
                return false
            }
        } catch (e) {
            console.log(this.constructor.name, `[${this.file.name}]`, config.name, e)
            return false
        }
    }

    async folder(config: CreatorFolderOutConfig) {
        try {
            //file names
            const startFullName = `${config.name}`
            //file pathes
            const startFullPath = path.resolve(config.path, startFullName)
            //operations
            const isExist = await utils.checkExist(startFullPath)
            const canBeWrited = !isExist || (isExist && config?.replaceExisting)
            if (canBeWrited) {
                await utils.remove(startFullPath)
                await fs.mkdir(startFullPath)
                return true
            } else {
                return false
            }
        } catch (e) {
            console.log(this.constructor.name, `[${this.folder.name}]`, config.name, e)
            return false
        }
    }
}

export default new Creator()
