'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var spawn = require( 'child_process').spawn;
var argv = require('yargs').argv;

require('./release');

var doPublish = function(done) {
    var publishArg = argv._[0];

    const additionalArgs = {
        "publish-beta": ["--tag", "beta"]
    };
    const tagArgs = {
        "publish-tag": ["--tag", argv.tag]
    };

    let args = ['publish'];
    if (additionalArgs[publishArg]) {
        args.push(...additionalArgs[publishArg]);
    }
    else if (tagArgs[publishArg]) {
      args.push(...tagArgs[publishArg]);
    }

    const isWin = process.platform === "win32";
    var publishCmd = isWin ? 'npm.cmd' : 'npm';

    const spawnPublish = (cwd) => {
        return new Promise((resolve, reject) => {
            var proc = spawn(publishCmd, args, { cwd: cwd });

            proc.stdout.on( 'data', data => {
                gutil.log( `stdout: ${data}` );
            });

            proc.stderr.on( 'data', data => {
                gutil.log( `stderr: ${data}` );
            });

            proc.on( 'close', code => {
                gutil.log(`child process exited with code ${code}`);
                resolve();
            });
        });
    };

    spawnPublish().then(() => {
        return spawnPublish('dist/@formbird/types');
    }).then(() => {
        return spawnPublish('dist/@formbird/shared');
    }).then(() => {
        return spawnPublish('dist/@formbird/angular-shared');
    }).then(() => {
      return spawnPublish('dist/@formbird/services');
    }).then(() => {
        return spawnPublish('projects/styles');
    }).finally(() => {
        done();
    });
};

var doPush = done => {
    var proc = spawn('git', [ 'push', '--follow-tags']);

    proc.stdout.on( 'data', data => {
        gutil.log( `stdout: ${data}` );
    } );

    proc.stderr.on( 'data', data => {
        gutil.log( `stderr: ${data}` );
    } );

    proc.on( 'close', code => {
        gutil.log(`child process exited with code ${code}`);
        done();
    });
};

gulp.task('publish', gulp.series('clean', 'release', doPublish, doPush));
