/*
 * grunt-wp-i18n
 * https://github.com/cedaro/grunt-wp-i18n
 *
 * Copyright (c) 2014 Cedaro, LLC
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function( grunt ) {

	var async = require( 'async' ),
		path = require( 'path' ),
		localConfig = require( './lib/util' ).init( grunt ).getLocalConfig(),
		wp = require( './lib/wordpress' ).init( grunt );

	/**
	 * Add the text domain to gettext functions.
	 *
	 * @link http://develop.svn.wordpress.org/trunk/tools/i18n/
	 */
	grunt.registerMultiTask( 'addtextdomain', 'Add the text domain to gettext functions.', function() {
		var done = this.async(),
			defaultI18nToolsPath = path.resolve( __dirname, '../vendor/wp-i18n-tools/' ),
			files = [],
			cmdArgs, o;

		o = this.options({
			i18nToolsPath: defaultI18nToolsPath,
			textdomain: '',
			updateDomains: []
		});

		// Use the Text Domain header or project folder name
		// if it hasn't been set.
		if ( '' === o.textdomain ) {
			o.textdomain = wp.getHeader( 'Text Domain' ) || wp.slugify();
		}

		o.i18nToolsPath = localConfig.i18nToolsPath || o.i18nToolsPath;

		// Make sure the add-textdomain.php script exists.
		o.addTextdomainScript = path.join( o.i18nToolsPath, 'add-textdomain.php' );
		if ( ! grunt.file.exists( o.addTextdomainScript ) ) {
			grunt.fatal( 'add-textdomain.php could not be found in ' + o.i18nToolsPath );
		}

		if ( true === o.updateDomains ) {
			o.updateDomains = ['all'];
		}

		// Build the list of CLI args.
		cmdArgs = [
			o.addTextdomainScript,
			'-i',
			o.textdomain,
			''
		];

		if ( grunt.option( 'dry-run' ) ) {
			cmdArgs[1] = '';
		}

		// Only add custom CLI args if using the bundled tools.
		if ( defaultI18nToolsPath === o.i18nToolsPath ) {
			// Use the custom CLI script that extends add-textdomain.php.
			o.addTextdomainScript = path.join( o.i18nToolsPath, 'grunt-add-textdomain.php' );

			cmdArgs[0] = o.addTextdomainScript;
			cmdArgs.push( o.updateDomains.join( ',' ) );
		}

		this.files.forEach(function( f ) {
			var filtered = f.src.filter(function( filepath ) {
				// Warn on and remove invalid source files (if nonull was set).
				if ( ! grunt.file.exists( filepath ) ) {
					grunt.log.warn( 'Source file "' + filepath + '" not found.' );
					return false;
				} else {
					return true;
				}
			});

			files = files.concat( filtered );
		});

		async.eachSeries( files, function( file, nextFile ) {
			cmdArgs[3] = path.resolve( process.cwd(), file );

			grunt.util.spawn({
				cmd: 'php',
				args: cmdArgs,
				opts: { stdio: 'inherit' }
			}, function() {
				nextFile();
			});
		}, function( error, result ) {
			done( error, result );
		});
	});

};
