'use strict';

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

function verifyInput(field, document){
    var value;

    if(!!document[field.name] && _.isString(document[field.name])){
        var saveValue = document[field.name];
        document[field.name] = document[field.name].toLowerCase();

        if(document[field.name] === "true" || document[field.name] === "false" ){
            value = JSON.parse(document[field.name]);
        }else{
            var errMsg = field.componentName + " field named " + field.name +
                " has invalid value \"" + saveValue + "\"";
            logger.error("Preprocessing Failure : " + errMsg);
            return null;
        }
    }

    return value;
}

var proceedVerification = function(input){
    if(_.isBoolean(input))
        return false;

    return true;
};

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

    var isProceed = proceedVerification(document[field.name]);

//    if(_.isEmpty(document[field.name]) && isProceed){
//        delete document[field.name];
//    }

    if(document[field.name]){
        if(isProceed){
            document[field.name] = verifyInput(field, document);

            if(_.isNull(document[field.name])){
                var errMsg = field.componentName + " field named " + field.name +
                    " has invalid value";
                deferred.reject(errMsg);
            }
        }
    }

    deferred.resolve(document);
  
    return deferred.promise;
};  