var fs = require('fs');
var fsp = fs.promises;
var path = require('path');
var crypto = require('crypto');


class File {
    static async Stat(p) {
        var stat = null;
        try {
            stat = await fsp.stat(p);
        } catch (e) { }
        return stat;
    }
    static async IsDir(p) {
        var stat = await this.Stat(p);
        if (stat) {
            return stat.isDirectory()
        } else {
            return false
        }
    }
    static async  IsFile(p) {
        var stat = await this.Stat(p);
        if (stat) {
            return stat.isFile()
        } else {
            return false
        }
    }
    static async  ReadDir(p) {
        var result = [];
        var dirs = await fsp.readdir(p);
        for (var i = 0; i < dirs.length; i++) {
            var dir = dirs[i];
            dir = path.join(p, dir);
            var s = await this.IsDir(dir)
            if (s) {
                var temp = await this.ReadDir(dir)
                result = result.concat(temp);
            } else {
                result.push(dir);
            }
        }
        return result;
    }
    static async  ReadDirEvent(p, event, eventKey) {
        var dirs = await fsp.readdir(p);
        for (var i = 0; i < dirs.length; i++) {
            var dir = dirs[i];
            dir = path.join(p, dir);
            var s = await this.IsDir(dir)
            if (s) {
                this.ReadDirEvent(dir, event, eventKey)
            } else {
                event.emit(eventKey, dir);
            }
        }
    }
    static async Md5(p, method = 'md5') {
        return new Promise((resolve, reject) => {
            var stream = fs.createReadStream(p)
            var c = crypto.createHash(method);
            stream.on('data', function (chunk) {
                c.update(chunk)
            })
            stream.on('end', function (chunk) {
                resolve(c.digest('hex'))
            })
        })
    }
    static FormatSize(size) {
        try {
            var level = 0;
            var levelMap = { 0: 'B', 1: 'KB', 2: 'MB', 3: 'GB' }
            while (size > 1024) {
                size /= 1024;
                level += 1;
            }
            return size.toFixed(2) + levelMap[level]
        } catch (error) {
            console.log(typeof size, size)
        }
    };
}

module.exports = File;