import { src, dest, watch, series, parallel } from 'gulp';
import yargs from 'yargs';
import sass from 'gulp-sass';
import cleanCss from 'gulp-clean-css';
import gulpIf from 'gulp-if';
import postcss from 'gulp-postcss';
import sourcemaps from 'gulp-sourcemaps';
import autoprefixer from 'autoprefixer';
import imagemin from 'gulp-imagemin';
import webpack from 'webpack-stream';
import named from 'vinyl-named';
import fileInclude from 'gulp-file-include'
import del from 'del';
import browserSync from "browser-sync";

const PRODUCTION = yargs.argv.prod;

export const styles = () => {
	return src(['source/sass/main.scss', 'source/sass/print.scss'])
		.pipe(gulpIf(!PRODUCTION, sourcemaps.init()))
		.pipe(sass().on('error', sass.logError))
		.pipe(gulpIf(PRODUCTION, postcss([ autoprefixer ])))
		.pipe(gulpIf(PRODUCTION, cleanCss({compatibility:'ie11'})))
		.pipe(gulpIf(!PRODUCTION, sourcemaps.write()))
		.pipe(dest('output/css/styles/inner'));
}

export const scripts = () => {
	return src(['source/js/index.js'])
		.pipe(named())
		.pipe(webpack({
			module: {
				rules: [
					{
						test: /\.js$/,
						use: {
							loader: 'babel-loader',
							options: {
								presets: []
							}
						}
					},
					{
						test: /\.css$/,
						use: [ 'style-loader', 'css-loader']
					},
				]
			},
			mode: PRODUCTION ? 'production' : 'development',
			devtool: /* !PRODUCTION ? 'eval-cheap-source-map' :*/ false,
			output: {
				filename: '[name].js'
			},
		}))
		.pipe(dest('output/js'));
}

export const images = () => {
	src('source/dummy/**/*.{jpg,jpeg,png,svg,gif}')
		.pipe(gulpIf(PRODUCTION, imagemin()))
		.pipe(dest('output/dummy'));
	return src('source/img/**/*.{jpg,jpeg,png,svg,gif}')
		.pipe(gulpIf(PRODUCTION, imagemin()))
		.pipe(dest('output/img'));
}

export const copy = () => {
	src(['source/services/**/*'])
		.pipe(dest('output/services/'));
	return src(['source/fonts/**/*'])
		.pipe(dest('output/fonts/'));
}

export const html = () => {
	return src(['./source/pages/*'])
		.pipe(fileInclude({
			prefix: '@@',
			basepath: './source/includes/'
		}))
		.pipe(dest('./output/'));
}

export const clean = () => del(['output']);

const server = browserSync.create();
export const serve = done => {
	server.init({
		proxy: "http://localhost/ihk24/templates/output"
	});
	done();
};
export const reload = done => {
	server.reload();
	done();
};

export const watcher = () => {
	watch('source/sass/**/*.scss', series(styles, reload));
	watch(['source/img/**/*.{jpg,jpeg,png,svg,gif}', 'source/dummy/**/*.{jpg,jpeg,png,svg,gif}'], series(images, reload));
	watch(['source/fonts/**/*'], series(copy, reload));
	watch('source/js/**/*.js', series(scripts, reload));
	watch(['source/pages/**/*', 'source/includes/**/*'], series(html, reload));
}

export const dev = series(clean, parallel(html, styles, scripts, images, copy), serve, watcher);
export const build = series(clean, parallel(html, styles, scripts, images, copy));

export default dev;
