'use strict';

var q = require("q");
var ElasticIndexingService= require('../../search/ElasticIndexingService');
var dbConfig = require('../providers/DatabaseConfig');

function findCounter(id) {
    return DBProvider.counterService.findCounter(id);
}
function insertCounter(counterFieldName, counterDocumentId, userId) {
    return DBProvider.counterService.insertCounter(counterFieldName, counterDocumentId, userId);
}

module.exports = {
    increase: function(counterDocumentId, counterFieldName, userId) {
        var deferred = q.defer();

        DBProvider.counterService.updateCounter(counterDocumentId, counterFieldName)
            .then(function successFunc(results) {
                if (results && results.value) {
                    var doc = results.value;
                    var indexId = DBProvider.counterService.getIndexId(doc);
                    var dsConfig = dbConfig.getDataServicesConfig();
                    ElasticIndexingService.index(indexId, doc, dsConfig);

                    deferred.resolve(results.value);
                } else {
                    var errorMsg = "Error retrieving counter document." +
                        " Ensure counter document exists: " + counterDocumentId;
                    logger.error(errorMsg);
                    deferred.reject(errorMsg);
                }

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

        return deferred.promise;
    }
};
