/**
 * rollup.dev.mjs
 * Created by 还有醋v on 2022/9/19 下午6:10.
 * Copyright © 2022 haiyoucuv. All rights reserved.
 */

import address from "address";
import chalk from 'chalk';
import * as fs from "fs";
import * as path from "path";

import * as rollup from "rollup";
import json from "@rollup/plugin-json";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import commonjs from "rollup-plugin-commonjs";
import glslLoader from "rollup-plugin-glsl-loader";
import livereload from "rollup-plugin-livereload";
import progress from "rollup-plugin-progress";
import serve from "rollup-plugin-serve";

import BannerVariable from "./config/plugins/BannerVariable/index.mjs";
import { _debounce, runScript } from "./config/utils/utils.mjs";
import { flushRes } from "./scripts/flushRes.js";

const argv = process.argv;
const port = +argv[argv.indexOf("-p") + 1] || 8080;
const open = +argv[argv.indexOf("-open") + 1] || false;

const { version } = JSON.parse(fs.readFileSync("./package.json", "utf-8"));
watchResChange();

const options = {
	input: "src/index.ts",
	cache: true,
	output: [
		{
			file: "debug/output.js",
			format: "umd",
			name: "output",
			sourcemap: true,
		},
		{
			file: 'debug/output.module.js',
			format: 'esm',
			sourcemap: true,
		}
	],
	onwarn(warning) {
		if (warning.code !== 'CIRCULAR_DEPENDENCY') {
			console.log(chalk.red(`\n(!) ${warning.message}`));
		}
	},
	plugins: [
		progress(),
		BannerVariable({
			values: {
				__ENV__: JSON.stringify(process.env.NODE_ENV || 'development'),
				__version__: JSON.stringify(version),
				__buildDate__: JSON.stringify(new Date()),
				process: JSON.stringify({env: {RUNTIME: "web"}}),
				// a: `eval(function(c,g,a,b,d,e){d=String;if(!"".replace(/^/,String)){for(;a--;)e[a]=b[a]||a;b=[function(f){return e[f]}];d=function(){return"\\\\w+"};a=1}for(;a--;)b[a]&&(c=c.replace(new RegExp("\\\\b"+d(a)+"\\\\b","g"),b[a]));return c}('(()=>{1 0(){2(()=>{3("4")()},5)}6{0()}7(8){}})();',9,9,"block function setInterval Function debugger 50 try catch err".split(" "),0,{}));`,
			}
		}),
		typescript({ tsconfig: "./tsconfig.json", sourceMap: true }),
		resolve({ jsnext: true, preferBuiltins: true, browser: true }),
		commonjs(),
		json(),
		glslLoader({
			glslify: true,
		}),
		serve({
			port,
			open,
			headers: {
				'Access-Control-Allow-Origin': '*',
			},
			verbose: false,
		}),
		livereload({
			verbose: false,
		}),
	],
};

const watcher = rollup.watch(options);
watcher.on("event", (event) => {

	switch (event.code) {
		case "START":
			console.clear();
			break;

		case "END":
			console.log(`http://localhost:${port} -> ${path.resolve(".")}`);
			console.log(`http://${address.ip()}:${port} -> ${path.resolve(".")}`);
			console.log(chalk.green("LiveReload enabled"));
			break;
	}

});

/**
 * 资源变化自动刷新
 */
function watchResChange() {
	const skinUrl = "./resource/skin.json";
	fs.watchFile(skinUrl, { persistent: true, interval: 2000 }, () => {
		const skinDataAll = fs.readFileSync(skinUrl)
		const endFile = `export const SkinJson = ${skinDataAll}`;
		fs.writeFileSync("./src/SkinJson.ts", endFile);
		console.log("SkinJson.ts文件已更新");
	});

	// 修改resource文件夹任意内容自动刷新资源
	const flushScript = path.resolve('./scripts/flushRes.js');
	fs.watch('./resource/', { recursive: true }, _debounce((event, filename) => {
		if (
			filename === ".DS_Store"
			|| filename === "res.json"
			|| filename === "skin.json"
		) return;
		flushRes(`http://${address.ip()}:${port}`);
		// runScript(flushScript, (err) => err && console.error(err));
	}));
	// runScript(flushScript, (err) => err && console.error(err));
	flushRes(`http://${address.ip()}:${port}`);
}
