'use strict';

const SharedConstants  = require('../../shared/constants/SharedConstants');
const isEmpty = require('lodash/isEmpty');

function constructFileReferenceDocument(fileRef, doc, fileReferenceTemplateId, fileUploaderConfig, cb) {

  var templateId;
  if (!isEmpty(fileReferenceTemplateId) && fileReferenceTemplateId !== 'undefined') {
    templateId = fileReferenceTemplateId;
  }
  else if (fileUploaderConfig && !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);
    cb(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 }
    ];
    cb(null, refDoc);
  }
}

module.exports = {
  constructFileReferenceDocument
};
