"use strict";

var q = require("q");
var counterService;

var getCounterService = function() {
    if (!counterService) {
        counterService = require('../dataServices/CounterService');
    }
    
    return counterService;
};

module.exports.preProcess = function(component, document, userId) {
    var deferred = q.defer();
    var tmpStr = component.format;

    var date = new Date();
    var YY = date.getFullYear().toString().substr(2, 3);
    YY = ("0" + YY).slice(-2);
    var MM = date.getMonth() + 1;
    MM = ("0" + MM).slice(-2);
    var DD = date.getDate();
    DD = ("0" + DD).slice(-2);

    tmpStr = tmpStr.replace("YY", YY);
    tmpStr = tmpStr.replace("MM", MM);
    tmpStr = tmpStr.replace("DD", DD);

    if (document[component.name]) {
        var msg = "Value exists, exit reference pre process";
        logger.info(msg);
        deferred.resolve(document);
    }
    else if (!component.counterFieldName || !component.counterDocumentId) {
        deferred.reject(new Error("Incorrect reference no. definition. Please add the counterDocumentId and counterFieldName"));
    } else {
        getCounterService().increase(component.counterDocumentId, component.counterFieldName, userId)
            .then(function successFunc(counterDocument) {

                if(!counterDocument[component.counterFieldName])
                    counterDocument[component.counterFieldName] = 0;
                
                tmpStr = tmpStr.replace("#", counterDocument[component.counterFieldName]);
                document[component.name] = tmpStr;

                deferred.resolve(document);
            }, function errorFunc(err) {
                deferred.reject(err);
            });
    }

    return deferred.promise;
};