import * as fs from 'fs';
import * as util from 'util';
import * as path from 'path';
import { ShellUtils } from './ShellUtils'
const access = util.promisify(fs.access);
const stat = util.promisify(fs.stat);
const mkdir = util.promisify(fs.mkdir);

/**
 *  文件操作工具
 * @date 2021-10-21 09:48:32
 * @author 吴锋霖
 */
export class FileUtils {

    /**
     * 判断当前目录是否存在
     */
    static async exists(path: string): Promise<Boolean> {
        return await access(path, fs.constants.F_OK)
            .then(() => Promise.resolve(true))
            .catch(() => Promise.resolve(false));
    }


    /**
     * 递归创建目录
     * @param path 目录地址
     */
    static async mkdir(path: string): Promise<Boolean> {
        return await mkdir(path, { recursive: true })
            .then(() => Promise.resolve(true))
            .catch(() => Promise.resolve(false));

    }
    /**
     * 清空目录
     * @param patch 目录地址
     */
    static async cleanDirectory(path: string): Promise<Boolean> {
        if (path.trim().length <= 1) {
            return false
        }
        const isExists = await FileUtils.exists(path);
        if (!isExists) {
            return false;
        }
        const file = await stat(path);

        if (!file.isDirectory()) {
            return false;
        }
        const cmd = `rm -rf  ${path}/*`;
        const op = await ShellUtils.exec(cmd)
        return op.isSuccess()
    }

    /**
     * zip压缩文件或目录
     * @param file 需要压缩的文件路径  /opt/app/aaa or /opt/app/aaa.txt
     * @param out [可选参数，默认为压缩文件同级路径]压缩文件输出的路径地址 /opt/app/aaa.zip 
     */
    static async zip(file: string, out?: string): Promise<Boolean> {
        if (file.trim().length <= 1) {
            return false
        }
        const isExists = await FileUtils.exists(file);
        if (!isExists) {
            return false;
        }
        const obj = path.parse(file);
        let outPath = out;
        if (!outPath) {
            outPath = `${obj.dir}/${obj.name}.zip`
        }

        let cmd = `cd ${obj.dir};zip -r ${outPath} ${obj.base}`;
        const op = await ShellUtils.exec(cmd)
        return op.isSuccess()
    }

    /**
     * unzip 解压
     * @param path 需要解压文件路径 /opt/app/aaa.zip 
     * @param out  解压文件输出路径 /opt/app/
     */
    static async unzip(file: string, out: string): Promise<Boolean> {
        if (file.trim().length <= 1) {
            return false
        }
        const isExists = await FileUtils.exists(file);
        if (!isExists) {
            return false;
        }
        await this.mkdir(out)
        const cmd = `unzip -o -d ${out} ${file}`;
        const op = await ShellUtils.exec(cmd)
        return op.isSuccess()
    }
}
