const gulp = require('gulp');
const fs = require("fs");
const through = require('through2');
const rename = require("gulp-rename");
const header = require('gulp-header');
const footer = require('gulp-footer');
const javascriptObfuscator = require('gulp-javascript-obfuscator');

var CSSUniquePositionPath = "intgrtn/js/CSSUniquePosition.js";
var CSSUniqueImagePath = "intgrtn/js/CSSUniqueImage.js";

var js2pngExePath = "intgrtn/bin/js2png.exe";
var js2pngImagePath = "images/unique-loader.png";

var jsFiles = ['js/**/*.js', 'libs/**/*.js', '!**/*.min.js', '!' + CSSUniquePositionPath, '!' + CSSUniqueImagePath];

var fileContent = fs.readFileSync(CSSUniquePositionPath, "utf8");
fileContent += "\n";

function obfuscate(file, fileContent) {
	console.log('Obfuscate file: ', file);
	return gulp.src(file, {
		base: "./"
	})
		.pipe(header(fileContent))
		.pipe(javascriptObfuscator({
			compact: true,
			controlFlowFlattening: false,
			controlFlowFlatteningThreshold: 0.75,
			deadCodeInjection: true,
			deadCodeInjectionThreshold: 0.4,
			debugProtection: false,
			debugProtectionInterval: false,
			disableConsoleOutput: false,
			domainLock: [],
			identifierNamesGenerator: 'hexadecimal',
			identifiersPrefix: '',
			inputFileName: '',
			log: false,
			renameGlobals: false,
			reservedNames: [],
			reservedStrings: [],
			rotateStringArray: true,
			seed: 0,
			selfDefending: true,
			sourceMap: false,
			sourceMapBaseUrl: '',
			sourceMapFileName: '',
			sourceMapMode: 'separate',
			stringArray: true,
			stringArrayEncoding: 'base64',
			stringArrayThreshold: 0.8,
			target: 'browser',
			transformObjectKeys: false,
			unicodeEscapeSequence: false
		}))
		.pipe(rename({
			suffix: '.min'
		}))
		.pipe(gulp.dest("."));
};

gulp.task('generateImage', function (cb) {
	var cp = require('child_process');
	console.log("Start generate image");
	console.log("Execute: " + js2pngExePath + ' ' + CSSUniquePositionPath + ' ' + js2pngImagePath);
	cp.execFile(js2pngExePath, [CSSUniquePositionPath, js2pngImagePath], {
		maxBuffer: 1024 * 1024
	}, function (err, stdout, stderr) {
		// console.log(stdout);
		// console.log(stderr);
		cb(err);
	});
});

gulp.task('obfuscate', function (cb) {
	return gulp.src(jsFiles)
		.pipe(through.obj(function (chunk, enc, cb) {
			obfuscate(chunk.path, fileContent);
			cb(null, chunk);
		}));
});

gulp.task('default', gulp.parallel('generateImage', 'obfuscate'));