/*
	Licensed Material - Property of IBM

	(C) Copyright 2015 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


'use strict';

var strings = require('ibm-strings');

module.exports.getError = function(errorCode) {
  // turn arguments object into an arrray, then remove the first item, what
  // remains is used to replace templated areas of the error description
  var replaceArgs = Array.prototype.slice.call(arguments).slice(1);

  var errorDefinition = require('./error-codes');

  return generateError(errorDefinition[errorCode], replaceArgs);
};

// Generate the error that will be returned
function generateError(newError, replaceArgs) {
  try {
    var customError = new Error(newError.code);
    customError.errno = newError.errno;
    customError.code = newError.code;
    var formatArgs = [newError.description].concat(replaceArgs);
    customError.description = strings.format.apply(this, formatArgs);

    return customError;
  } catch (e) {
    return null;
  }
}
