var gulp = require('gulp');
var lessToScss = require('gulp-less-to-scss');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const watch = require('gulp-watch');
const cssmin = require('gulp-cssmin');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('serve', function () {
    "use strict";
    browserSync.init({
        proxy: "http://lms.loc",
        host: "192.168.0.124",
        port: 3000,
        notify: true,
        ui: {
            port: 3001
        },
        open: false
    });
});

gulp.task('watch', function () {
    watch('./assets/scss').on('change', (e) => {
        let directory = e.split('masterstudy');
        directory = directory[1];

        let dest = './assets/css/';

        let path = directory.replace('scss', 'css').split('/');
        let path2 = path.pop();

        if(directory.indexOf('vc_modules') !== -1) {
            dest = '.';
            path.forEach(function(v){
                dest += v + '/';
            });
        } else if(path2[0] === '_') {
            directory = '/assets/scss/*.scss';
        }

        gulp.src(['.' + directory])
            .pipe(sourcemaps.init())
                .pipe(sass().on('error', sass.logError))
                .pipe(autoprefixer())
                .pipe(cssmin())
            .pipe(sourcemaps.write('../sourcemap'))
            .pipe(gulp.dest(dest))
            .pipe(browserSync.stream())
    });
});

gulp.task('default', ['watch', 'serve']);

















gulp.task('lessToScss',function(){
    gulp.src('./assets/css/*.less')
        .pipe(lessToScss())
        .pipe(gulp.dest('./assets/scss/'));

    gulp.src('./assets/css/less_components/wordpress_core.less')
        .pipe(lessToScss())
        .pipe(gulp.dest('./assets/scss/scss_components'));
});