'use strict';

var SharedConstants = require('../../shared/constants/SharedConstants');
var AccessManager = require('../../shared/access/AccessManager');
var ServerConstants = require('../constants/ServerConstants');
var UtilArray = require('../../shared/utils/UtilArray');

/**
 * Read the offline data for sending to a device
 *
 * @param accountId
 * @param startTime
 */
module.exports.getOfflineDocuments = function(accountId, startTime, pageNumber, numberPerPage) {
    var countOnly = false;
    return queryOfflineDocuments(accountId, startTime, countOnly, pageNumber, numberPerPage);
};

/**
 * Read the offline document and its template for sending to a device
 * @param accountId
 * @param startTime
 * @param pageNumber
 * @param numberPerPage
 * @returns {*}
 */
module.exports.getOfflineTemplateDocuments = function (accountId, startTime, pageNumber, numberPerPage) {
    var countOnly = false;
    return queryOfflineDocuments(accountId, startTime, countOnly, pageNumber, numberPerPage).then(
        function successFunc(documents) {
            var templateIds = [];
            for (var i = 0; i < documents.length; i++) {
              if (documents[i] && documents[i].systemHeader && documents[i].systemHeader.templateId) {
                UtilArray.add(templateIds, documents[i].systemHeader.templateId, true);
              }
            }
            return queryOfflineTemplates(accountId, templateIds).then(
                function okFunc(templates) {
                    return Promise.resolve({
                        documents: documents,
                        templates: templates
                    });
                },
                function failFunc(error) {
                    return Promise.reject(error);
                }
            );
        },
        function errorFunc(err) {
            return Promise.reject(err);
        }
    );
};

/**
 * Returns the number of documents expected when you fetch unsync docs using getOfflineDocuments.
 * @param accountId
 * @param startTime
 */
module.exports.getOfflineSyncCount = function(accountId, startTimeDate){
    var countOnly = true;
    return queryOfflineDocuments(accountId, startTimeDate, countOnly);
};

//Generic query function
function queryOfflineDocuments(accountId, startTime, countOnly, pageNumber, numberPerPage){
    var dbProvider = require('../database/providers/DatabaseProvider')();
    var offlineDataService = dbProvider.offlineDataService;

    var startTimeDate = getMillis(startTime);

    return offlineDataService.getOfflineDocuments(accountId, startTimeDate, countOnly, pageNumber, numberPerPage);
};

//Generic query function
function queryOfflineTemplates(accountId, templateIds){
    var dbProvider = require('../database/providers/DatabaseProvider')();
    var offlineDataService = dbProvider.offlineDataService;

    return offlineDataService.getOfflineTemplates(accountId, templateIds);
};

// the start time is passed in as an integer of the number of milliseconds since the epoch (1/1/1970).
// Convert the start time to a date object if it exists
// when coming from restful web services, the start time will be a string representation of the epoch value.
// Eg. "1470371018088"

function getMillis(startTime){

    if(!startTime){
        return null;
    }

    var startTimeNumber = parseInt(startTime);
    var valid = startTimeNumber && !Number.isNaN(startTimeNumber);

    return valid ?  new Date(startTimeNumber) : null;
}
