'use strict';

var q = require("q");
var SearchService = require('../search/SearchService');
var SharedConstants  = require('../../shared/constants/SharedConstants');
var lodashLang = require('lodash/lang');
const SharedUtilFileReference = require('../../shared/utils/UtilFileReference');
const service = {

    createReferenceDocument : function(fileRef, doc, userId, fileReferenceTemplateId) {
        var deferred = q.defer();
        var fileUploaderConfig = config.get("fileUploader");
        SharedUtilFileReference.constructFileReferenceDocument(fileRef, doc, fileReferenceTemplateId,
          fileUploaderConfig,(err, refDoc) => {
            if (err){
              deferred.reject(err);
            } else {
              DataService.insert(refDoc, userId)
                .then(function successFunc(data) {
                  logger.info('Created reference document ' + data.documentId + ' for ' + fileRef.fileNo + '.');
                  deferred.resolve(data);
                }, function errorFunc(err) {
                  var msg = 'Failed to create reference document for ' + fileRef.fileNo + ' to ' + doc.documentId + '.';
                  logger.error(err.message);
                  deferred.reject(new Error(msg));
                });
            }
        });

        return deferred.promise;
    },

    fetchReferenceDocument : function(fileNo, userId){

        var cnf = config.get("fileUploader");
        var fieldn = cnf ? cnf.fileUploaderField : null;

        if(!fieldn){
            return q.reject(new Error('Invalid fileReference configuration.'));
        }
        const fileReferenceService = require('../database/dataServices/FileReferenceService');
        return fileReferenceService.fetchFileReferenceDocument(fieldn, fileNo, userId)
            .then(function successFunc(data) {
                return data[0];
            }, function errorFunc(err) {
                return q.reject(err);
            });
    },

    getFileFieldName: function () {

        var cnf = config.get("fileUploader");
        return cnf ? cnf.fileUploaderField : null;
    },

    getParentDocFieldName: function () {

        var cnf = config.get("fileUploader");
        return cnf ? cnf.relatedDocumentField : null;
    },

    // Uses DataService.destroy for soft deleting the file reference document.
    // Soft delete sets the systemHeader.deleted flag to false.
    destroyFileReference : async function(fileNo, userId){
        const fileReference = await service.fetchReferenceDocument(fileNo, userId);
        if (fileReference == null){
            return; // nothing to destroy
        }
        return DataService.destroy(fileReference.documentId, userId);
    }
};

module.exports = service;
