'use strict';

var q = require("q");
var MongoConnection = require('./MongoConnection');
var logger = require('../../../utils/Logger').loggers.get('db');

/**
 * get offline documents based on the keys. The keys in documents will be matched against accessKeys on the account with a key name
 * of "Offline"
 * @param userId
 * @returns {*|promise}
 */
function getOfflineDocuments(accountId, startTime, countOnly, pageNumber, numberPerPage) {
    var deferred = q.defer();

    /* sync all documents where the user has a key with a right of offline. This is specified in the accessKeys element
     of the account Eg in the following documents with the keyId of the first entry under accessKeys would be synced because
     it has "Offline" in the rights:

     "accessKeys" : [
     {
     "keyId" : "7BC98642-529D-4423-94AD-5063CE262280",
     "rights" : [
     "Create",
     "Update",
     "Read",
     "Offline"
     ]
     },
     {
     "keyId" : "172CAD42-7E31-4A65-ACAE-82ABF8BB09E4",
     "rights" : [
     "Create",
     "Update",
     "Read"
     ]
     }
     */

    // create MongoDB query to get offline documents
    var offlineQuery;

    // only pass in an offline query if the startTime is defined. Otherwise all documents matching the offline key will be returned

    if (startTime) {
        offlineQuery = {"systemHeader.serverUpdatedDate": {$gt: startTime}};
    } else {
        offlineQuery = {};
    }
    offlineQuery["systemHeader.versionId"] = {$exists:true};
    offlineQuery["documentId"] = {$exists:true};
    offlineQuery["documentId"] = {'$regex': /^[0-9a-zA-Z-]+$/ };

    // sort in asc order
    var sortQuery = {'systemHeader.serverUpdatedDate': 1};
    var allVersions = false;

    // query for documents with the Offline key and no others
    var options = {
        alternativeKey: SharedConstants.OPERATION_TYPE_OFFLINE,
        excludeMissingKeys: true // exclude documents that don't have any keys, because we only want to cache documents that have
                                 // the offline key
    };
    options.countOnly = countOnly;
    options.pageNumber = pageNumber;
    options.numberPerPage = numberPerPage;

    DataService.findAll(offlineQuery,
        accountId,
        sortQuery,
        allVersions,
        options
    ).then(
        function successFunc(documents) {
            logger.info("Got documents to sync for offline use of count: " + (documents.length ? documents.length : documents));
            deferred.resolve(documents);
        }, function errorFunc(err) {
            logger.error("Error getting offline documents: " + err);
            deferred.reject(err);
        }
    );

    return deferred.promise;
}

/**
 * get offline templates based on the keys. The keys in documents will be matched against accessKeys on the account with a key name
 * of "Offline"
 * @param userId
 * @returns {*|promise}
 */
function getOfflineTemplates(accountId, templateIds) {
    var deferred = q.defer();

    // create MongoDB query to get offline documents
    var offlineQuery = {"documentId": {$in: templateIds}};
    var allVersions = false;

    // query for documents with the Offline key and no others
    var options = {
        alternativeKey: SharedConstants.OPERATION_TYPE_OFFLINE,
        excludeMissingKeys: true // exclude documents that don't have any keys, because we only want to cache documents that have
        // the offline key
    };

    DataService.findAll(offlineQuery,
        accountId,
        null,
        allVersions,
        options
    ).then(
        function successFunc(templates) {
            logger.info("Got templates to sync for offline use of count: " + (templates.length ? templates.length : templates));
            deferred.resolve(templates);
        },
        function errorFunc(err) {
            logger.error("Error getting templates: " + err);
            deferred.reject(err);
        }
    );

    return deferred.promise;
}

////////////////////////////////////
// public api
module.exports = {
    getOfflineDocuments: getOfflineDocuments,
    getOfflineTemplates: getOfflineTemplates
};
