'use strict';

var q = require("q");
var logger = require('../../../utils/Logger').loggers.get('db');
var CouchbaseConnection = require('./CouchbaseConnection');
var SharedConstants = require('../../../../shared/constants/SharedConstants');
var UtilDocumentId = require('../../../../shared/utils/UtilDocumentId');
var DataService = require("../../DataService");
var cbUtil = require('./CouchbaseUtil');

var COUNTER_ID_PREFIX = "counter_";

var findCounter = function(documentId, connectionName){
    var deferred = q.defer();

    if (!documentId) {
        logger.debug("id not provided in findCounter");
        deferred.reject(new Error("An id must be provided in the findCounter function"));
    } else {
        var cbBucket = CouchbaseConnection.getBucket(connectionName);
        var bucketName = CouchbaseConnection.getConfig(connectionName).bucket;

        var statement = "SELECT `" + bucketName + "`.* FROM `" + bucketName + "` " +
            "WHERE documentId = $1 AND systemHeader.currentVersion = true;";

        var query = cbUtil.getN1QlQuery(statement);
        cbBucket.query(query, [documentId], function(err, results) {
            if (err) {
                deferred.reject(err);
            } else {
                if (results && results.length !== 0) {
                    deferred.resolve(results[0]);
                } else {
                    var errorMsg = "Error retrieving counter document." +
                        " Ensure counter document exists: " + documentId;
                    deferred.reject(errorMsg);
                }
            }
        });
    }

    return deferred.promise;
};

var updateCounter = function(documentId, counterFieldName, connectionName){
    var deferred = q.defer();
    var cbBucket = CouchbaseConnection.getBucket(connectionName);

    findCounter(documentId, connectionName).then(function(counterDoc) {
        var counterId = COUNTER_ID_PREFIX + documentId;
        cbBucket.counter(counterId, 1, {initial: 1}, function(err, result) {
            if (err) {
                deferred.reject(err);
            } else {
                counterDoc[counterFieldName] = result.value;
                counterDoc.systemHeader.serverUpdatedDate = new Date();

                cbBucket.replace(documentId, counterDoc, function (err, res) {
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve({value: counterDoc});
                    }
                });
            }
        });
    }, function(err) {
        deferred.reject(err);
    });

    return deferred.promise;
};


module.exports = {
    updateCounter: updateCounter,

    getIndexId : function(document){
        return document.documentId;
    }
};