var gulp = require('gulp');
var path = require('path');
var fileSystem = require('fs');
var sass = require('gulp-sass');

/**
 * task that compiles scss files under target/assets/styles/ and writes only styles.css (the only file that should be published). 
 * All other scss files are deleted from target/assets/styles/.
 */
gulp.task(
  "custom:after-assets-copy",
  () => {
    var styleDest = path.join(configuration.distAssetsFolder, configuration.packageName, "styles");
    return gulp.src([`${styleDest}/*.scss`, `^${styleDest}/_*.scss`])
      .pipe(sass({
        outputStyle: 'compressed',
        includePaths: [`${styleDest}/"`]
      }))
      .pipe(gulp.dest(styleDest))
      .on('end', function () {
        return fileSystem.readdirSync(styleDest).forEach((file) => {
          var curPath = path.join(styleDest, file);
          if (fileSystem.lstatSync(curPath).isDirectory()) { 
            emptyFolder(curPath);
            fileSystem.rmdirSync(curPath);
          } else if (file.endsWith(".scss")){
            fileSystem.unlinkSync(curPath);
          }
        })
      });
  }
);

function emptyFolder(directoryPath) {
  if (fileSystem.existsSync(directoryPath)) {
    fileSystem.readdirSync(directoryPath).forEach(function (file) {
      var curPath = path.join(directoryPath, file);
      if (fileSystem.lstatSync(curPath).isDirectory()) { 
        emptyFolder(curPath);
        fileSystem.rmdirSync(curPath);
      } else { 
        fileSystem.unlinkSync(curPath);
      }
    });
  }
}

gulp.task('custom:after-all', function (){
  var mainTask = process.argv.slice(2)[0];
  if (mainTask === 'build:watch_local') {
    var dest = path.join(process.cwd(), '..', 'pdca0-deploy-arch', 'node_modules', '@isp', 'xdce-module-widget-fideuram-v1');
    if (fileSystem.existsSync(dest)){
       emptyFolder(dest);
    }
    return gulp.src(`${configuration.distFolder}/**`)
      .pipe(gulp.dest(dest));
  }
});