/**
 Gulp Requirements
 */
var gulp = require('gulp'),
    merge = require('gulp-merge'),
    concat = require('gulp-concat'),
    less = require('gulp-less'),
    sourcemaps = require('gulp-sourcemaps'),
    log = require('fancy-log'),
    minimist = require('minimist'),
    nfs = require('fs'),
    npath = require('path'),
    browserSync = require('browser-sync');


/**
 --shopId <Number> Set Shopware Shop ID
 --excludeSWtheme  If given, Shopware Responsive Theme will be excluded
 */
var cliflags = {
    default: {
        shopId: process.env.NODE_ENV || 1,
        excludeSWtheme: process.env.NODE_ENV || false
    }
};

var shopId = minimist(process.argv.slice(2), cliflags).shopId,
    file = './web/cache/config_' + shopId + '.json',
    config = require(file),
    pathObject = npath.parse(config.lessTarget),
    jsFiles = [],
    content = '',
    excludeSWtheme = minimist(process.argv.slice(2), cliflags).excludeSWtheme,

    targetThemeSrc = '/themes/Frontend/amds_cla/frontend/_public/src',
    jsSearchPattern = '$/js/jquery.**.js',
    proxyUrl = 'https://cla.de';


/**
 Some Basic Paths

 pathObject returns
 { root: '',
   dir: 'web/cache',
   base: 'timestamp_hash.css',
   ext: '.css',
   name: 'timestamp_hash'
 }

 */
var path = {
    build: './' + pathObject.dir,
    lessSource: './' + pathObject.dir + '/' + pathObject.name + '.less',
    jsTarget: pathObject.name + '.js',
    globalVariables: {},
    modifyVariables: {
        'font-directory': '"/themes/Frontend/Responsive/frontend/_public/src/fonts"',
        'webfont-directory': '"/themes/Frontend/amds_cla/frontend/_public/vendors/fonts"'
    },
    watch: {
        less: [

            './themes/Frontend/**/*.less'
        ],
        js: [
            './themes/Frontend/**/frontend/_public/src/js/*.js',
            '!./themes/Frontend/**/frontend/_public/src/js/vendors/*.js'
        ]
    }
};


/**
 Generate LESS Includes, extracted from config_SHOPID.json,
 and exclude Shopware Responsive Theme if CLI Flag "--excludeSWtheme"
 is given
 */
config['less'].forEach(function (item) {
    if (excludeSWtheme) {
        if (item === 'themes/Frontend/Responsive/frontend/_public/src/less/all.less') {
            item = '';
        }
    }
    if (item !== '') {
        content += '@import "./' + item + '";';
    }
    content += "\n";
});
nfs.writeFileSync(path.lessSource, content);


/**
 Get all Shopware JS includes, that will be injected at the Bottom
 */
config['js'].forEach(function (item) {
    jsFiles.push('./' + item);
});


/**
 Fill Array with Shopware Theme Settings
 */
for (var key in config.config) {
    path.globalVariables[key] = config.config[key];
}


/**
 LESS Development
 */
gulp.task('less', function () {
    return gulp.src(path.lessSource)
        .pipe(sourcemaps.init())
        .pipe(less({
            globalVars: path.globalVariables,
            modifyVars: path.modifyVariables,

            // however it doen't work for me...
            relativeUrls: true
            //
        })).on('error', function (err) {
            log(err);
        })
        .pipe(sourcemaps.write())
        // .pipe(sourcemaps.write('.', {
        //     sourceMappingURLPrefix: '/' + pathObject.dir
        // }))
        .pipe(gulp.dest(path.build)).on('error', function (err) {
            log(err);
        })
        .pipe(browserSync.reload({stream: true}));
});


/**
 JS Development
 */
function js() {
    var swjs = gulp.src(jsFiles),
        customjs = gulp.src(targetThemeSrc + jsSearchPattern);

    // Merge two Stream 1) Shopware Theme Scripts, 2) Custom Theme Scripts
    return merge(swjs, customjs)
        .pipe(concat(path.jsTarget))
        .pipe(gulp.dest(path.build))
}


function server(done) {
    browserSync.init({
        open: false,
        online: true,
        reloadOnRestart: true,
        proxy: proxyUrl,
        serveStatic: [{
            route: 'web/cache',
            dir: 'web/cache'
        }],
        notify: {
            styles: {
                top: 'auto',
                bottom: '0',
                borderRadius: '5px 0px 0px'
            }
        }
    });
    done();

}



function watch() {
    gulp.watch(path.watch.less).on('all',gulp.series('less'));
    gulp.watch(path.watch.js).on('all', gulp.series(js, browserSync.reload));
}

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