const fs = require('fs')
const path = require('path')
const project = require('../../project')

const PLACEHOLDER_DIC = {
    "XCODE_TEMPLATE_PROJECT": RegExp("XCODE_TEMPLATE_PROJECT", 'ig'),
    "XcodeTemplateProject": RegExp("XcodeTemplateProject", 'ig'),
    "rn_lib": RegExp("rn_lib", 'ig'),
}

const IGNORES = [
    '.buckconfig', '.eslintrc.js', '.flowconfig', '.git', '.gitattributes',
    '.gitignore', '.prettierrc.js', '.watchmanconfig', 'node_modules',
    'ios/Pods', 'gradle-wrapper.jar', 'debug.keystore', '.jpg', '.gif', '.png'
]

function _ignoresFilter(item) {
    for (let i = 0; i < IGNORES.length; i++) {
        if (item.path.includes(IGNORES[i])) {
            return false
        }
    }
    return true
}

/*
* 修改文件夹名称跟文件名称
*/
function applyProjectName(replaceName, projectName) {
    let PLACEHOLDER_RE = PLACEHOLDER_DIC[replaceName]
    const files = project.fs.allFilesAndDirectories(_ignoresFilter)
    // 替换文件名和文件内容
    files.filter(item => item.file).forEach(item => {
        let oldPath = path.resolve(item.path)

        // 文件内容替换
        let data = fs.readFileSync(oldPath).toString()
        if (PLACEHOLDER_RE.test(data)) {
            console.debug(`处理内容 ${path.relative(process.cwd(), oldPath)}`)
            data = _resolvePlaceholder(data, replaceName, projectName)
            fs.writeFileSync(oldPath, data)
        }

        // 文件名称替换
        let { dir, base } = path.parse(oldPath)
        if (PLACEHOLDER_RE.test(base)) {
            console.debug(`重命名文件 ${path.relative(process.cwd(), oldPath)}`)
            let newBase = _resolvePlaceholder(base, replaceName, projectName)
            let newPath = path.resolve(dir, newBase)
            fs.renameSync(oldPath, newPath)
        }
    })

    // 替换文件夹名
    files.filter(item => !item.file).forEach(item => {
        let oldPath = path.resolve(item.path)
        let { dir, base } = path.parse(oldPath)
        if (PLACEHOLDER_RE.test(base)) {
            console.debug(`重命名目录 ${path.relative(process.cwd(), oldPath)}`)
            // 忽略大小写替换文件夹名 android 是小写
            let newBase = _resolvePlaceholder(base, replaceName, projectName)
            let newPath = path.resolve(dir, newBase)
            fs.renameSync(oldPath, newPath)
        }
    })
}

function _resolvePlaceholder(src, replaceName, dest) {
    let PLACEHOLDER_RE = PLACEHOLDER_DIC[replaceName]
    return src.replace(PLACEHOLDER_RE, found => {
        if (found === replaceName.toLowerCase()) {
            return dest.toLowerCase()
        }
        return dest
    })
}

module.exports.applyProjectName = applyProjectName
