const fs = require('fs');
const path = require('path');
const Os = require('os');
const { exec } = require('child_process');


/** 压缩引擎路径表 */
const enginePathMap = {
	/** macOS */
	'darwin': 'pngquant/macos/pngquant',
	/** Windows */
	'win32': 'pngquant/windows/pngquant'
}

const platform = Os.platform();
const pngquantPath = path.join(__dirname, enginePathMap[platform]);
// 设置引擎文件的执行权限（仅 macOS）
if (pngquantPath && platform === 'darwin') {
	if (fs.statSync(pngquantPath).mode != 33261) {
		// 默认为 33188
		fs.chmodSync(pngquantPath, 33261);
	}
}

const qualityParam = `--quality 60-80`;
const speedParam = `--speed 3`;
const skipParam = '--skip-if-larger';
const outputParam = '--ext=.png';
const writeParam = '--force';
const compressOptions = `${qualityParam} ${speedParam} ${skipParam} ${outputParam} ${writeParam}`;


// 要处理的图片文件夹路径
const altasPath = path.join(__dirname, "../released/resource/");

const folders = getFolders(altasPath);
const files = folders.map((folder) => {
	return altasPath + folder + '/*.png';
})

console.time("压缩时间：");
// compress([`${altasPath}**/*.png`]); // 这个慢很多，但是可以多层级

// 这个快很多，但是只能一层级
compress(files)
	.then(() => {
		console.timeEnd("压缩时间：");
	});


/**
 * 压缩
 * @param {string[]} pathArr 文件数组
 * @param {object} options 压缩参数
 */
async function compress(pathArr, options = compressOptions) {
	const tasks = [];

	pathArr.forEach((filePath, i) => {
		if (!filePath) {
			console.error(i, filePath);
			return;
		}
		// 加入压缩队列
		tasks.push(new Promise((resolve) => {
			try {
				const command = `"${pngquantPath}" ${filePath} ${options}`;
				exec(command, (error, stdout, stderr) => {
					if(stderr) console.error(stderr);
					resolve();
				});
			} catch (e) {
				console.error(e);
				resolve();
			}
		}));
	});

	await Promise.all(tasks);
}


function getFolders(dir) {
	return fs.readdirSync(dir)
		.filter(function (file) {
			return fs.statSync(path.join(dir, file)).isDirectory();
		});
}
