'use strict';

var q = require("q");
var _ = require('lodash/lang');
var passwordHelper = require('../../account/PasswordHelper');
var logger = require('../../utils/Logger').loggers.get('db');
var SharedConstants = require('../../../shared/constants/SharedConstants');
var PasswordChecker = require('../../account/password/PasswordChecker');
var accountService = require('../dataServices/AccountService');
var UtilError = require('../../utils/UtilError');

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 originalDocumentField = document[field.name];

    if (!originalDocumentField) {
        deferred.resolve();
    }
    else if (!originalDocumentField.newPass && !originalDocumentField.confirmPass) {
        deferred.resolve();
    }
    else if (!originalDocumentField.newPass || !originalDocumentField.confirmPass) {
        deferred.reject("Both the new password and a confirmation of the password must be provided to set the password");
    }
    else if (originalDocumentField.newPass !== originalDocumentField.confirmPass) {
        deferred.reject("Passwords do not match");
    }
    else {
        var ruleBreaches = PasswordChecker.evaluatePassword(originalDocumentField.newPass, config.get('passwordCreationRules'));

        if(ruleBreaches.length > 0){
            deferred.reject(PasswordChecker.createSimpleErrMessageStr(ruleBreaches));
        } else {
            passwordHelper.createHash(originalDocumentField.newPass, function (hash) {
                if (document.systemHeader.systemType === SharedConstants.SYSTEM_TYPE_ACCOUNT) {
                    let resolveDocument = () => {
                        if (originalDocumentField.newPass && originalDocumentField.newPass !== "*") {
                            document[field.name] = "*";
                        } else {
                            // delete password field, password should be in accountSecurityDocument
                            delete document[field.name];
                        }

                        deferred.resolve(document);
                    };

                    accountService.updateAccountSecurityPassword(document.documentId, "password", hash).then(() => {
                        resolveDocument();
                    }, (e) => {
                        if (e instanceof UtilError.AccountNotFoundError) {
                            logger.warn("Account not found in DB.");
                            resolveDocument();
                        } else {
                            deferred.reject(e);
                        }
                    });
                } else {
                    // set the hashed password in the document
                    document[field.name] = hash;
                    deferred.resolve(document);
                }
            });
        }
    }


    return deferred.promise;
};  