"use strict";

const gulp            = require("gulp");
const ngrok           = require("ngrok");
const chokidar        = require("chokidar");
const sass            = require("gulp-sass");
const shell           = require("gulp-shell");
const rename          = require("gulp-rename");
const minify          = require("gulp-clean-css");
const autoprefix      = require("gulp-autoprefixer");
const server          = require("gulp-develop-server");
const gearworksConfig = require("./gearworks.private.json");

gulp.task("sass", () =>
{
    const cssMinOptions = {
        processImport: false,
        processImportFrom: ['!fonts.googleapis.com']
    }
    
    return gulp.src(['css/**/*.scss'])
        .pipe(sass())
        .pipe(autoprefix())
        .pipe(minify(cssMinOptions))
        .pipe(rename((path) => 
        {
            path.extname = ".min.css";
        }))
        .pipe(gulp.dest('wwwroot/css'));
})

gulp.task("default", ["sass"]);

gulp.task("watch", ["default"], (cb) =>
{
    const ngrokConfig = {
        addr: gearworksConfig["gearworks-port"] || 3000,
        subdomain: gearworksConfig["gearworks-ngrokSubdomain"],
    }

    ngrok.connect(ngrokConfig, (err, url) =>
    {
        if (err) throw err;

        console.log("Started ngrok on", url);

        gearworksConfig["gearworks-ngrokDomain"] = url.replace(/^.*:\/\//i, "");

        server.listen({path: "bin/server.js", env: gearworksConfig});
    })
    
    // Gulp.watch in 3.x is broken, watching more files than it should. Using chokidar instead.
    // https://github.com/gulpjs/gulp/issues/651
    chokidar.watch(["bin/**/*.js"], {ignoreInitial: true}).on("all", (event, path) =>
    {
        server.restart();
    });

    chokidar.watch(sassTask.files, {ignoreInitial: true}).on("all", (event, path) =>
    {
        console.log(`${event}: Sass file ${path}`);
        
        if (path.indexOf("_variables.scss") > -1)
        {
            //Recompile all sass files with updated variables.
            return sassTask.task(gulp.src(sassFiles));
        }
        
        return sassTask.task(gulp.src(path));
    })
    
    shell.task("pouchdb-server -n --dir pouchdb --port 5984")();
})
@@ -504,32 +504,75 @@
 );%0A%0A
-gulp.task(%22sass%22, (
+const sassFiles = %5B%22css/**/*.scss%22%5D;%0Aconst sassTask = (gulpSrc
 ) =%3E
-%0A
+ 
 %7B%0A  
@@ -710,31 +710,11 @@
 gulp
-.src(%5B'css/**/*.scss'%5D)
+Src
 %0A   
@@ -890,16 +890,16 @@
     %7D))%0A
-
         
@@ -931,16 +931,87 @@
 css'));%0A
+%7D%0A%0Agulp.task(%22sass%22, () =%3E%0A%7B%0A    return sassTask(gulp.src(sassFiles));%0A
 %7D)%0A%0Agulp
@@ -1825,14 +1825,9 @@
 sass
-Task.f
+F
 iles

Fix gulp sass task