'use strict';

var q = require("q");
var lodashObject = require('lodash/object');
var lodashLang = require('lodash/lang');
var SharedConstants = require('../../../shared/constants/SharedConstants');
var logger = require('../../utils/Logger').loggers.get('db');

var checkListSeparator;

function validateInput(field, document){
    //check first if the given input matches values in the checklist
    var validatedValue = [];
    if(!!document[field.name] && isValidValueType(document[field.name])){
        var saveValue = document[field.name];
        if(typeof document[field.name] === 'string'){
            // setup the checkListSeparator from config if not defined
            if (!checkListSeparator) {
                var CsvDefaults = config.get('CsvDefaults');
                checkListSeparator = (CsvDefaults) ? CsvDefaults.checkListSeparator : SharedConstants.checkListSeparator;
            }
        
            var val = document[field.name].split(checkListSeparator);
            setItemValue(document, field.name, val);
        }

        if(document[field.name].length > 0){
            for(var i = 0; i < document[field.name].length; i++){
                if(field.list.indexOf(document[field.name][i]) !== -1){
                    validatedValue.push(document[field.name][i]);
                }else{
                    var errMsg = field.componentName + " field named " + field.name +
                        " has invalid value \"" + saveValue + "\"";
                    logger.error("Preprocessing Failure : " + errMsg);
                    return null;
                }
            }
        }
        return validatedValue;
    }
};

var isValidValueType = function(value){
    return lodashLang.isString(value) || lodashLang.isArray(value) || lodashLang.isObject(value);
};

var setItemValue = function(obj, prop, val){
    lodashObject.set(obj, prop, val);
};

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

//    if(lodashLang.isEmpty(document[field.name])){
//        delete document[field.name];
//    }

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

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

    deferred.resolve(document);

    return deferred.promise;
};