import * as fs from "fs";
import * as path from "path";
import JSZIP from "jszip";

//��ȡĿ¼���ļ�
function readDir(zip, nowPath) {
    const files = fs.readdirSync(nowPath);
    files.forEach(function (fileName, index) {//�������Ŀ¼�е��ļ�
        console.log(fileName, index);//��ӡ��ǰ��ȡ���ļ���
        const fillPath = nowPath + "/" + fileName;
        const file = fs.statSync(fillPath);//��ȡһ���ļ�������
        if (file.isDirectory()) {//�����Ŀ¼�Ļ���������ѯ
            const dirlist = zip.folder(fileName);//ѹ�����������ɸ�Ŀ¼
            readDir(dirlist, fillPath);//���¼���Ŀ¼�ļ�
        } else {
            // �ų�ͼƬ�ļ�
            if (fileName.endsWith(".png") || fileName.endsWith(".jpg")) {
                return;
            }
            zip.file(fileName, fs.readFileSync(fillPath));//ѹ��Ŀ¼�����ļ�
        }
    });
}

//��ʼѹ���ļ�
export function zipDir(name, dir, dist) {
    return new Promise<void>((resolve, reject) => {
        const zip = new JSZIP();
        readDir(zip, dir);
        zip.generateAsync({//����ѹ����ʽ����ʼ���
            type: "nodebuffer",//nodejs��
            compression: "DEFLATE",//ѹ���㷨
            compressionOptions: {//ѹ������
                level: 9
            }
        }).then(function (content) {
            // @ts-ignore
            fs.writeFileSync(`${dist}/${name}.zip`, content, "utf-8");
            resolve();
        });
    });
}

