const gulp = require('gulp');
const path = require('path');
const fs = require('fs-extra');
const CC = require('@meesvdw/coloredconsole');
const ts = require('gulp-typescript');
const concat = require('gulp-concat');
const cleanCSS = require('gulp-clean-css');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const { argv } = require('process');
var sass = require('gulp-sass')(require('sass'));
var tap = require('gulp-tap');
var browserify = require('browserify');
var buffer = require('gulp-buffer');

exports.default = () => {
	var pageIndex = argv.includes('-page') ? argv.indexOf('-page') : null;
	var pageName = pageIndex != null && pageIndex + 1 < argv.length ? argv[pageIndex + 1] : null;

	var layoutIndex = argv.includes('-layout') ? argv.indexOf('-layout') : null;
	var layoutName = layoutIndex != null && layoutIndex + 1 < argv.length ? argv[layoutIndex + 1] : null;

	if (pageName == null && layoutName == null)
		return console.log(
			CC.red +
				CC.bright +
				`\n\nIncorrect syntax. Please use '-page [pagename]' or '-layout [layoutname]'\n\n` +
				CC.reset
		);

	var directoryType = pageName ? 'Page' : 'Layout';
	var directoryName = pageName ? pageName : layoutName;
	var directoryQuery = pageName ? pageName : `layouts/${layoutName}`;

	var basePath = path.join(__filename, '..', 'pages', directoryQuery);
	fs.pathExists(basePath, (err, exists) => {
		if (exists == false)
			return console.log(
				CC.red + CC.bright + `\n\n${directoryType} ${directoryName} does not exist\n\n` + CC.reset
			);
		else {
			buildTypescript(basePath, () =>
				buildSass(basePath, () => {
					console.log(CC.green + CC.bright + `Watcher running` + CC.reset);
					gulp.watch(
						[
							`pages/${directoryQuery}/ts/**/*.ts`
						],
						(finish) => {
							console.log(CC.blue + CC.bright + `Typescript change detected` + CC.reset);
							buildTypescript(basePath, finish);
						}
					);

					gulp.watch(
						[
							`pages/${directoryQuery}/sass/**/*.scss`
						],
						(finish) => {
							console.log(CC.magenta + CC.bright + `Sass change detected` + CC.reset);
							buildSass(basePath, finish);
						}
					);
				})
			);
		}
	});
};

function buildTypescript(basePath, cb) {
	var tsProject = ts.createProject(path.join(basePath, 'tsconfig.json'));
	gulp
		.src(path.join(basePath, 'ts', '**', '*.ts'))
		// .pipe(
		// 	tap(function(file) {
		// 		file.contents = browserify(file.path, { debug: true }).bundle();
		// 	})
		// )
		// .pipe(buffer())
		.pipe(tsProject())
		.js.pipe(concat(`script.js`))
		.pipe(rename(`script.js`))
		.pipe(uglify())
		.pipe(gulp.dest(basePath))
		.on('end', () => {
			cb();
		});
}

function buildSass(basePath, cb) {
	gulp
		.src(path.join(basePath, 'sass', '**', '*.scss'))
		.pipe(sass().on('error', sass.logError))
		.pipe(cleanCSS({ compatibility: 'ie8' }))
		.pipe(concat(`style.css`))
		.pipe(rename(`style.css`))
		.pipe(gulp.dest(basePath))
		.on('end', () => {
			cb();
		});
}
