import chalk from "chalk";

import AutoUpload from "../Uploader/Uploader.ts";
import * as path from "path";
import {findFiles} from "../commom/helper.ts";
import {compressAllImage} from "../AssetsMin/ImageCompress.ts";
import {compressAllSvga} from "../AssetsMin/SvgaCompress.ts";
import ProgressBar from "progress";

interface IDuibaPublishOptions {
  buildVersion: string | number,
  uploadDir: string,
  accessKeySecret: string,
  accessKeyId: string,
  bucket: string,
  region: string,
}

export default function DuibaPublish(options: IDuibaPublishOptions) {

  const {
    buildVersion,
    uploadDir,
    accessKeySecret,
    accessKeyId,
    bucket,
    region,
  } = options;

  return {
    name: 'duiba-publish',

    async closeBundle() {

      // 资源压缩
      console.log(chalk.green("开始资源压缩了"));

      console.log(chalk.green("开始压缩图片了"));
      const imgPaths = findFiles(path.resolve("dist"), /\.png$/);

      const bar = new ProgressBar(`压缩图片进度 [:bar] :current/${imgPaths.length} :percent :elapseds`, {
        complete: "●",
        incomplete: "○",
        width: 20,
        total: imgPaths.length,
        callback: () => {
          console.log("%cAll complete.", "color: green");
        }
      })

      await compressAllImage(imgPaths, (cur, total) => {
        bar.tick();
      });

      console.log(chalk.green("\n压缩图片结束了\n"));

      // 资源压缩
      console.log(chalk.green("开始压缩Svga了"));
      const svgaPaths = findFiles(path.resolve("dist"), /\.svga$/);

      await compressAllSvga(svgaPaths, (cur, total) => {
        // process.stdout.write(chalk.green(`\r压缩Svga进度：${cur}/${total}`));
      });

      console.log(chalk.green("\n压缩Svga结束了\n"));


      console.log(chalk.green("开始上传了"));

      const autoUpload = new AutoUpload({
        dir: path.resolve("dist"),
        originDir: `/${uploadDir}/${buildVersion}/`,
        accessKeySecret, accessKeyId, bucket, region,
      });


      await autoUpload.start();

      console.log(`${chalk.green(`上传成功，版本号: ${buildVersion}`)}`);

    }
  }
}
