'use strict';

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

var searchList = function(field, list, val, listName){

    if(!lodashLang.isArray(list) && listName){
        var found = false;
        var i = 0;
        while(!found && i < field[listName].length){
            if(field[listName][i].item.indexOf(val) !== -1){
                found = true;
            }
            i++;
        }

        if(found){
            return val;
        }else{
            return displayError(field, val);
        }

    }else{
        if(list.indexOf(val) !== -1){
            return val;
        }else if (lodashLang.isEqual(val, "Default Value") || lodashLang.isEqual(val, "")){
            return "";
        }else{
            return displayError(field, val);
        }
    }
};

function displayError(field, val){
    var errMsg = field.componentName + " field named " + field.name +
        " has invalid value \"" + val + "\"";
    logger.error("Preprocessing Failure : " + errMsg);
    return null;
}

function validateInput(field, document){

    var validatedValue;

    if(!!document[field.name] && lodashLang.isString(document[field.name])){
        var saveValue = document[field.name].trim();
        var list = null;
        var listName = field.type;

        listName = lodashString.camelCase(listName.replace(/ +/g, ""));
        if(listName.search('List') === -1)
            listName+="List";

        if(lodashObject.has(field, listName))
            list = lodashObject.get(field, listName);

        if(list){
            var i=0;
            while(!lodashLang.isObject(list[i]) && i < list.length) i++;

            var dropDownEx = list[i];

            if(dropDownEx){
                validatedValue = searchList(field, dropDownEx, saveValue, listName);
            }else{
                validatedValue = searchList(field, list, saveValue);
            }

        }
    }
    return validatedValue;
}

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

module.exports.preProcess = function(field, document){

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

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

        if(lodashLang.isNull(document[field.name]) || lodashLang.isUndefined(document[field.name])){
            const errMsg = field.componentName + " field named " + field.name + " has invalid value";
            return Promise.reject(new Error(errMsg));
        }
    }


    return Promise.resolve(document);
};
