'use strict';

var q = require("q");
var logger = require('../../utils/Logger').loggers.get('db');

module.exports.preProcess = function(field, document) {
	var deferred = q.defer();

	if (document[field.name]) {
		var saveValue = document[field.name];
		var errMsg = field.componentName + " field named " + field.name +
			" has invalid value \"" + saveValue + "\"";
		var typeOfField = typeof document[field.name];

		if (typeOfField === 'number') {
			deferred.resolve(document);
		} else {
			try {
				var numeric = parseFloat(document[field.name]);
				if (isNaN(numeric)) {
					logger.error("Preprocessing Failure : " + errMsg);
					deferred.reject(errMsg);
				} else {
					document[field.name] = numeric;
					deferred.resolve(document);
				}
			} catch (err) {
				logger.error("Preprocessing Failure : " + errMsg);
				deferred.reject(errMsg);
			}
			
		}
	} else {
        deferred.resolve(document);
    }

	return deferred.promise;
};