/**
 * GKA (generate keyframes animation)
 * author: joeyguo
 * HomePage: https://github.com/joeyguo/gka
 * MIT Licensed.
 *
 */

const fs   = require("fs"),
    path   = require("path"),
    mkdirp = require('mkdirp');

const writeFile = (src, dest) => {
    return new Promise((resolve, reject) => {
        let writeStream = fs.createWriteStream(dest).on('finish', resolve);
        fs.createReadStream(src).pipe(writeStream);
    })
}

module.exports = class ImageFlattenPlugin {
    constructor() {}
    apply(compiler) {
        compiler.hooks.on('transform', (context, next) => {
            let {
                options,
                data,
                fileSystem,
            } = context;

            let tmpDir = path.join(fileSystem.tmpdir, 'flatten', data.ratio);
            
            let {
                frames,
                animations
            } = data;

            // pass by
            if (Object.keys(animations).length === 1) return next(context);

            mkdirp(tmpDir, function (err) {

                let pr = [];
                for (let key in animations) {
                    let p = animations[key].map((fIndex, i) => {

                        let src = frames[fIndex]['src'],
                            filepath = path.join(tmpDir, path.basename(src));

                        // TODO 将名字进行修改成 folder_filename, 否则多文件夹的同名文件会出现覆盖
                        // 下面方式会导致文件名被修改，需改成文件夹形式
                        // filepath = path.join(tmpDir, (key !== '' ? key + '_' + path.basename(src) : path.basename(src)));
                    
                        frames[fIndex]['src'] = filepath;
                        return writeFile(src, filepath)
                    })
                    pr = pr.concat(...p)
                }
                Promise.all(pr).then(() => {
                    console.log('[+] flatten');
                    next(context);
                });
            })
        })
    }
}
@@ -1223,17 +1223,17 @@
 %5D%5B'src'%5D
-,
+;
 %0A       
@@ -1245,27 +1245,30 @@
             
-   
+// let
  filepath = 
@@ -1338,105 +1338,45 @@
  // 
-TODO %E5%B0%86%E5%90%8D%E5%AD%97%E8%BF%9B%E8%A1%8C%E4%BF%AE%E6%94%B9%E6%88%90 folder_filename, %E5%90%A6%E5%88%99%E5%A4%9A%E6%96%87%E4%BB%B6%E5%A4%B9%E7%9A%84%E5%90%8C%E5%90%8D%E6%96%87%E4%BB%B6%E4%BC%9A%E5%87%BA%E7%8E%B0%E8%A6%86%E7%9B%96%0A                        // %E4%B8%8B%E9%9D%A2%E6%96%B9%E5%BC%8F%E4%BC%9A%E5%AF%BC%E8%87%B4%E6%96%87%E4%BB%B6%E5%90%8D%E8%A2%AB%E4%BF%AE%E6%94%B9%EF%BC%8C%E9%9C%80%E6%94%B9%E6%88%90%E6%96%87%E4%BB%B6%E5%A4%B9%E5%BD%A2%E5%BC%8F
+ rename the file to %22folder_filename%22
 %0A   
@@ -1396,18 +1396,19 @@
         
-//
+let
  filepat
@@ -1403,36 +1403,42 @@
  let filepath = 
-path
+fileSystem
 .join(tmpDir, (k
@@ -1461,20 +1461,26 @@
 + '_' + 
-path
+fileSystem
 .basenam
@@ -1488,20 +1488,26 @@
 (src) : 
-path
+fileSystem
 .basenam

rename the file to "folder_filename"