const fs = require('fs');
const path = require('path');


/**
 * 检测制定目录是否存在，如果不存在就生成，如果是文件就报错, 多次同一目录检测只会执行一次
 * @param  {string} dirname 上传文件的目录
 */
async function mkdir(dirname) {
    let state = await new Promise((resolve, reject) => {
        fs.stat(dirname, (err, stats) => {
            if (err) {
                resolve(-1);
            } else if (stats.isDirectory()) {
                resolve(0);
            } else {
                resolve(1);
            }
        });
    });
    
    if (state === 1) {
        throw `upload module error ${dirname} is File`;
    } else if (state === 0) {
        return;
    } 

    await mkdir(path.dirname(dirname));

    try {
        await new Promise((resolve, reject) => {
            fs.mkdir(dirname, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    } catch(e) {
        throw `upload module create dir ${dirname} error ${e.message}`;
    }
}

module.exports = exports = mkdir;