'use strict';

const utilHttpStatus =  require('../../shared/utils/UtilHttpStatus');
let OfflineDataReader;


let offlineConfig = config.get('offline') ? config.get('offline') : {};
if (!offlineConfig.syncPageSize) {
  //default
  offlineConfig.syncPageSize =100;
}


exports.syncDocuments = function(req, res) {

  var userId = req.user ? req.user.documentId : null;

  if (!userId) {
    var msg = "No logged in user in call to syncDocuments";
    logger.error(msg);
    res.status(utilHttpStatus.UNAUTHORIZED).send(msg);
    return;
  }

  if (!OfflineDataReader) {
    OfflineDataReader = require('../offline/OfflineDataReader');
  }

  var startTime = req.params.startTime;
  var pageNumber = req.params.pageNumber;
  var numberPerPage = offlineConfig.syncPageSize;

  OfflineDataReader.getOfflineTemplateDocuments(userId, startTime, pageNumber, numberPerPage).then(
    function successFunc(offlineTemplateDocuments) {
      res.set('Content-Type', 'application/bson');
      res.send(offlineTemplateDocuments);
    }, function errorFunc(err) {
      res.status(utilHttpStatus.INTERNAL_SERVER_ERROR).send(err);
    });
};

exports.getSyncDocumentCount = function (req, res) {

  var userId = req.user ? req.user.documentId : null;

  if (!userId) {
    var msg = "No logged in user in call to syncDocumentCounts";
    logger.error(msg);
    res.status(utilHttpStatus.UNAUTHORIZED).send(msg);
    return;
  }

  if (!OfflineDataReader) {
    OfflineDataReader = require('../offline/OfflineDataReader');
  }

  var startTime = req.params.startTime;

  OfflineDataReader.getOfflineSyncCount(userId, startTime)
    .then(function successFunc(docCount) {
      logger.info("Got documents to sync for offline use of count: " + docCount);

      var pages = Math.ceil(docCount / offlineConfig.syncPageSize);
      var result = {
        docCount: docCount,
        syncPageSize: offlineConfig.syncPageSize,
        pages: pages
      };
      logger.info(JSON.stringify(result));
      res.json(result);
    }, function errorFunc(err) {
      res.write(err);
      res.end();
    });
};
