/**
 * Create tag on git.
 * @function ci.worker.tagOnGit
 * @param {object} config - Task configuration
 * @param {string} config.versionFile - Version file name.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */

var childProcess = require('child_process'),
    util = require('util'),
    path = require('path'),
    fs = require('fs'),
    debug = require('./_debug'),
    format = util.format,
    exec = childProcess.exec;

exports = module.exports = function (config, callback) {
    var version = fs.readFileSync(path.resolve(config.versionFile)).toString().trim();
    var tagName = format('v%s', version);
    if (!tagName) {
        callback(new Error('Tag name is required'));
        return;
    }
    exports._tagExists(tagName, function (err, exists) {
        if (err) {
            callback(err);
            return;
        }
        if (exists) {
            var duplicateErr = format('Tag %s already exists.', tagName);
            callback(new Error(duplicateErr));
            return;
        }
        exports._addTag(tagName, function (err) {
            if (err) {
                callback(err);
                return;
            }
            exports._pushTags(function (err) {
                if (!err) {
                    debug('New tag created: %s', tagName);
                }
                callback(err);
            });
        });
    });


};

/**
 * Find out if a tag exists of not.
 * @param {string} tagName - Tag name to find out.
 * @param {function} callback - Callback when done.
 * @private
 */
exports._tagExists = function (tagName, callback) {
    var command = format('git tag -l %s', tagName);
    exec(command, function (err, stdOut, stdErr) {
        callback(err || stdErr || null, !!stdOut);
    });
};

/**
 * Add new tag.
 * @param {string} tagName - Tag name to add.
 * @param {function} callback - Callback when done.
 * @private
 */
exports._addTag = function (tagName, callback) {
    var command = format('git tag %s', tagName);
    exec(command, function (err, stdOut, stdErr) {
        callback(err || stdErr || null);
    });
};

/**
 * Push tags.
 * @param {function} callback - Callback when done.
 * @private
 */
exports._pushTags = function (callback) {
    var command = 'git push --tags';
    exec(command, function (err, stdOut, stdErr) {
        callback(err || stdErr || null);
    });
};