'use strict';

var gulp = require('gulp');
var jsonModify = require('gulp-json-modify');
var filter = require('gulp-filter');
var exec = require('child_process').exec;
var gutil = require('gulp-util');

var m = require('../common.js');
var buildConfig = m.config.buildConfig;
var distDir = buildConfig.distDir;
var schematicDir = buildConfig.schematicDir;
var clientSrcDir = buildConfig.clientDir + '/**/*';
var serverSrcDir = buildConfig.serverDir + '/**/*';
var sharedSrcDir = buildConfig.sharedDir + '/**/*';
var tsFiles = '*.ts';
var angularFiles = 'angular.json';
var packageFiles = 'package.json';
var tsConfigFiles = 'tsconfig.json';

var processDist = function() {
  // copy all project info files, server/shared files except server/config/development.json
  // to dist and schematic folder
      var f = filter([
      '**/*',
      serverSrcDir + '/config/*',
      '!*server/public/**/*',
      '!*server/uploadDir/*',
      '!*server/log/*',
      '!*server/config/development.json']);
    gulp.src([
            // clientSrcDir,
            buildConfig.serverDir + '/config/*',
            // sharedSrcDir,
            tsFiles,
            angularFiles,
            packageFiles,
            tsConfigFiles
        ], {base: "."})
        .pipe(f)
        .pipe(gulp.dest(distDir))
        .pipe(gulp.dest(schematicDir));

    // gulp.src(distDir + '/**/*')
    //   .pipe(gulp.dest(schematicDir));

    // copy development.json to dist folder that it can be used in places not schematic
    gulp.src(buildConfig.serverDir + '/config/development.json', {base: "."})
        .pipe(gulp.dest(distDir));
};

var processSchematic = function() {
  gulp.src([buildConfig.serverDir + '/config/development.json'])
//    .pipe(jsonModify({
//      key: "dataServices.default.port",
//      value: '<%= port %>'
//    }))
    .pipe(jsonModify({
      key: "dataServices.default.db",
      value: '<%= formbirdDbName %>'
    }))
    .pipe(gulp.dest(schematicDir + '/server/config/'));
};

gulp.task('schematic', function () {

  //build project client code
  var buildCmd = '';

  //build schematic code
  buildCmd += 'cd fieldtec-schematic && yarn install && npm run build && cd ..';

  var options = {cwd: ""};
  exec(buildCmd, options, function (err, stdout, stderr) {
    gutil.log(stdout);
    gutil.log(stderr);

    //copy dist files to dist dir
    processDist();

    //copy fieldtec files to schematic resource
    processSchematic();

    //publish schematic internal
    var pubCmd = 'cd fieldtec-schematic && npm link';
    var opts = {cwd: ""};
    exec(pubCmd, opts, function (err, stdout, stderr) {
      gutil.log(stdout);
      gutil.log(stderr);
    });

    //publish schematic
//    var publishCmd = 'cd fieldtec-schematic && npm publish';
//    var options = {cwd: ""};
//    exec(publishCmd, options, function (err, stdout, stderr) {
//      gutil.log(stdout);
//      gutil.log(stderr);
//    });
  });

});
