const OSS = require('ali-oss');
const queue = require('queue');
const fs = require('fs');
const path = require('path');

let client = new OSS({
    region: 'oss-cn-shenzhen',
    accessKeyId: 'LTAI5tPoBCiEMSDaS1Q4HKr9',
    accessKeySecret: 'F8ZNiqdH35T7gikBkn6Fq8tgbvdY88',
    bucket: 'raex-meta'
});

class UploadCDNPlugin {
    constructor(basePath) {
        this.basePath = basePath + '/';
    }
    // Define `apply` as its prototype method which is supplied with compiler as its argument
    apply(compiler) {
        compiler.hooks.done.tapAsync('UploadPlugin', (stats, callback) => {
            let basePath = this.basePath;
            const q = queue({ results: [], concurrency: 16 });
            function uploadDir(dir) {
                fs.readdirSync(dir).forEach(child => {
                    if (/^\./.test(child)) return;
                    let file = path.resolve(dir, child);
                    let stat = fs.statSync(file);
                    if (stat.isDirectory()) {
                        uploadDir(file);
                    } else {
                        q.push(async cb => {
                            let relpath = path.relative(path.resolve(__dirname, 'dist'), file);
                            const result = await client.put(path.normalize(basePath + relpath), file);
                            console.log(result);
                            cb();
                        });
                    }
                });
            }
            uploadDir(path.resolve(__dirname, 'dist'));
            q.start(() => {
                callback();
            });
        });
    }
}
module.exports = UploadCDNPlugin;
