'use strict';

var gulp = require('gulp');
var m = require('../common.js');
var buildConfig = m.config.buildConfig;
var gutil = require('gulp-util');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');

// set up the watching of files so that the service worker will be rebuilt on file changes
m.serviceWorkerGlob = [
    buildConfig.clientAppDir + '/styles/**/*',
    buildConfig.clientAppDir + '/images/**/*',
    buildConfig.clientAppDir + '/fonts/**/*',
    buildConfig.clientAppDir + '/*.html',
    buildConfig.clientAppDir + '/*.webmanifest',
    buildConfig.clientAppDir + '/scripts/**/*.js'
];


const swFolder = "client/app/scripts/modules/core/serviceWorkers/";
const webpackConfig = require('./../../webpack.config.js');
const swDistFolder =  "dist/sw-dist/";
const buildServiceWorker = done => {

  return gulp.src(swFolder + "ServiceWorker.ts")
    .pipe(webpackStream(webpackConfig), webpack)
    .pipe(gulp.dest(swDistFolder)
    );

};
// generate the service worker for the app, which controls caching of static assets for offline use.
// This is called 'service-worker' rather than 'service-workers' because a web app can only
// have one service worker
const serviceWorker = done => {

    // build the service worker using the workbox service worker library
    const {injectManifest} = require('workbox-build');

    const swDest = buildConfig.publicDir + '/serviceWorker.js';

    injectManifest({
        "swDest": swDest,
        "globDirectory": "server/public",
        "globPatterns": [
            "**/*.{gif,eot,svg,ttf,woff,woff2,ico,png,jpg,js,css,ijmap,html}"],
        "globIgnores": [
            "vendor/custom-component-modules/**/*"
        ],
        "swSrc": swDistFolder + "ServiceWorker.js",
        "maximumFileSizeToCacheInBytes": 10 * 1024 * 1024 // cache a maximum of 10mb
    }).then(({count, size}) => {
        gutil.log(`Generated ${swDest}, which will precache ${count} files, totaling ${size} bytes.`);
    });

    done();
};

const ServiceWorkerStart = done => {
    //Move ServiceWorkerStart.js to public directory
    const swStartSrc = "client/app/scripts/modules/core/serviceWorkers/ServiceWorkerStart.js";
    return gulp.src(swStartSrc).pipe(gulp.dest(buildConfig.publicDir));
};

gulp.task('service-worker', gulp.series([buildServiceWorker, ServiceWorkerStart, serviceWorker]));
