import axios from 'axios';
import archiver from 'archiver';
import fs from 'fs';
import path from 'path';
import FormData from 'form-data';
import { config } from './config';
import urlJoin from 'url-join';

/**
 * zip folder
 *   sourceFolder，待压缩的文件夹
 *   destZip，压缩后的zip文件
 *   subdir，是否需要包一层
 */
function zipFolder({ sourceFolder, destZip }) {
  // init
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(destZip);
    const archive = archiver('zip', {
      zlib: { level: 9 },
    });
    console.log('zip 压缩中...');

    // on
    output.on('close', function () {
      console.log('zip压缩结束');
      resolve(null);
    });
    archive.on('error', function (err) {
      console.error('zip压缩失败', err);
      reject(err);
    });
    // zip
    archive.pipe(output);
    archive.directory(sourceFolder, false);
    archive.finalize();
  });
}

const getPath = (dir: string) => {
  return path.resolve(process.cwd(), dir);
};

const publish = async () => {
  const tempDestZipPath = getPath(config.destFoler + '.zip');
  console.log('destZipPath', tempDestZipPath);
  await zipFolder({
    sourceFolder: getPath(config.sourceFolder),
    destZip: tempDestZipPath,
  });
  const file = fs.createReadStream(tempDestZipPath);
  const formData = new FormData();
  formData.append('file', file);
  formData.append('dir', config.destFoler);
  if (config.reservedFiles) {
    formData.append('reservedFiles', JSON.stringify(config.reservedFiles));
  }
  console.log('开始上传', new Date().toLocaleString());
  axios
    .request({
      method: 'post',
      url: urlJoin(config.host, 'send'),
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    .then((res) => {
      console.log('上传成功', res.data);
    })
    .catch((err) => {
      console.error('上传失败', err, new Date().toLocaleString());
    })
    .finally(() => {
      console.log('上传结束', new Date().toLocaleString());
      // 上传完要删除临时压缩包
      fs.unlinkSync(tempDestZipPath);
    });
};

publish();
