'use strict';

var q = require("q");
var SearchService = require('../search/SearchService');
var SharedConstants  = require('../../shared/constants/SharedConstants');
var lodashLang = require('lodash/lang');

const service = {

    createReferenceDocument : function(fileRef, doc, userId, fileReferenceTemplateId) {
        var deferred = q.defer();

        var fileUploaderConfig = config.get("fileUploader");

        var templateId;
        if (!lodashLang.isEmpty(fileReferenceTemplateId) && fileReferenceTemplateId !== 'undefined'){
            templateId = fileReferenceTemplateId;
        }
        else if(fileUploaderConfig && !lodashLang.isEmpty(fileUploaderConfig.defaultTemplateId)){
            templateId = fileUploaderConfig.defaultTemplateId;
        }
        var docField = fileUploaderConfig.relatedDocumentField;
        var fileField = fileUploaderConfig.fileUploaderField;

        if (templateId == null || docField == null || fileField == null) {
            var errorMsg = 'Invalid configuration values for generating reference document.';
            logger.error(errorMsg);
            deferred.reject(new Error(errorMsg));
        } else {

            var refDoc = {
                systemHeader: {
                    systemType: SharedConstants.SYSTEM_TYPE_FILE_REFERENCE,
                    templateId: templateId
                }
            };

            // insert the file details {fileNo, fileName, fileType} - ft-uploader format
            refDoc[fileField] = [fileRef];
            // use the document id as default document name so a link can appear if you view the file reference document
            // in the app based on the format sent by the Uploader.js
            var docName = doc.name != null && doc.name !== 'undefined' ? doc.name : doc.documentId;
            // insert the document - ft-related-document format
            refDoc[docField] = [
                {documentId: doc.documentId, name: docName }
            ];

            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;
