/* File: gulpfile.js */

// grab our gulp packages
const gulp = require('gulp'),
    babel = require('gulp-babel'),
    del = require('del'),
    browser = require('browser-sync'),
    gulpif = require('gulp-if'),
    log = require('fancy-log'),
    autoprefixer = require('gulp-autoprefixer'),
    cleanCSS = require('gulp-clean-css'),
    sass = require('gulp-sass')(require('sass')),
    sourcemaps = require('gulp-sourcemaps'),
    webpack = require('webpack-stream'),
    plumber = require('gulp-plumber')


//

let paths = {
    html: '../Resources/Private/',
    styles: {
        src: '../Resources/Private/Scss/',
        dest: '../Resources/Public/Css/'
    },
    scripts: {
        src: '../Resources/Private/JavaScript/',
        dest: '../Resources/Public/JavaScript/'
    },

};

let project = {
    devurl: 'https://muehlherr.ddev.site',
    liveurl: 'https://muehlherr.de',
    extname: 'muehlherr_sitepackage',
    extdir: 'typo3conf/ext/' + this.extname + '/Resources/Public',
    additionalWatchedFolders: [
        '../../pathrepo/amds_bear/Resources/Private/'
    ]
}


// environmental settings for production/deployment

const $isProduction = (process.argv[3] == "--production"),
    $environment = (process.argv[4] == "--live" ? project.liveurl : project.devurl);


let isProduction = false,
    sourceMap = true,
    deployDev = true,
    deployLive = false;

if ($isProduction) {
    isProduction = true;
    sourceMap = false;
    deployDev = true;
    deployLive = true;
}


function clean(done) {
    del([
        '../Resources/Public/Css/**/*',
        '../Resources/Public/Javascript/Dist/**/*'
    ], {
        force: true
    });
    done();
}


// Less to CSS: Run manually with: "gulp build-css"
function stylesheet() {
    return gulp.src([paths.styles.src + 'theme.scss'])
        .pipe(gulpif(!$isProduction, sourcemaps.init()))
        .pipe(sass({
            includePaths: ['node_modules/']
        }))
        .pipe(autoprefixer())

        .pipe(gulpif($isProduction, cleanCSS({
                level: 1,
                format: (!$isProduction ? 'beautify' : 'none'),
            }, function (details) {
                console.log(details.name + ': ' + (details.stats.originalSize / 1024).toFixed(2) + '/' + (details.stats.minifiedSize / 1024).toFixed(2) + ' KB' + ' (-' + (details.stats.efficiency * 100).toFixed(2) + '%)')
            }
        )))
        .pipe(gulpif(!$isProduction, sourcemaps.write()))
        .pipe(gulp.dest(paths.styles.dest))

        .pipe(browser.reload({stream: true}));
}


function jsLibs() {
    return gulp.src([
        'node_modules/jquery/dist/jquery.slim.min.js'
    ])
        .pipe(gulp.dest(paths.scripts.dest)).on('error', function (err) {
            log(err);
        })
}

function cssLibs() {
    return gulp.src([], {allowEmpty: true})
        .pipe(gulp.dest(paths.styles.dest)).on('error', function (err) {
            log(err);

        })
}

function jsBootstrap() {
    return gulp.src([
        'node_modules/bootstrap/js/src/util.js',
        'node_modules/bootstrap/js/src/carousel.js',
        // 'node_modules/bootstrap/js/src/alert.js',
        'node_modules/bootstrap/js/src/collapse.js',
        'node_modules/bootstrap/js/src/dropdown.js',
        // 'node_modules/bootstrap/js/src/scrollspy.js',
        // 'node_modules/bootstrap/js/src/tab.js',
        // 'node_modules/bootstrap/js/src/popover.js',
        'node_modules/bootstrap/js/src/modal.js',
        // 'node_modules/bootstrap/js/src/tooltip.js',
        // paths.scripts.src + '/headroom.init.js',
        // paths.scripts.src + '/scrolltop.js',
        // paths.scripts.src + '/detectos.init.js',
        paths.scripts.src + '/bootstrap.init.js'
    ], {allowEmpty: true})
        .pipe(webpack(require('./webpack.config.js')))

        .pipe(gulp.dest(paths.scripts.dest)).on('error', function (err) {
            log(err);
        })
}


function server(done) {
    browser.init({
        open: false,
        online: true,
        reloadOnRestart: true,
        logConnections: true,
        proxy: $environment,
        https: true,
        // serveStatic: [{
        //     route: [project.extdir, 'typo3temp/assets/compressed'],
        //     dir: ['../Resources/Public/']
        // }],
        notify: {
            styles: {
                top: 'auto',
                bottom: '0',
                borderRadius: '5px 0px 0px'
            }
        }
    });
    done();
}


function watch() {
    gulp.watch(paths.styles.src + '**/*.scss').on('all', gulp.series(stylesheet));
    gulp.watch(paths.scripts.src + '**/*.js').on('all', gulp.series(jsLibs, jsBootstrap, browser.reload));
    // gulp.watch([].concat(paths.html, project.additionalWatchedFolders) + '**/*.html').on('all', browser.reload);
    gulp.watch([].concat(paths.html + '**/*.html', project.additionalWatchedFolders + '**/*.html') ).on('all', browser.reload);
}



// Build the "dist" folder by running all of the below tasks
// CSS HANDELD BY NEW WORKFLOW

gulp.task('build',
    gulp.series(clean, gulp.parallel(stylesheet, jsLibs, jsBootstrap))
);

// Build the site, run the server, and watch for file changes
gulp.task('default',
    gulp.series('build', server, watch)
);
