'use strict';

var SharedConstants = require('../constants/SharedConstants');
var UtilType = require('./UtilType');
const lodashObject = require('lodash/object');

var isNew = function(doc) {
    return !doc.systemHeader || !doc.systemHeader.createdDate;
};

var isPreviousVersion = function(doc) {
    return doc.systemHeader && doc.systemHeader.currentVersion === false;
};

var isDeleted = function(doc) {
    var deleted = doc.systemHeader ? doc.systemHeader.deleted : false;
    return deleted === true || deleted === 'true';
};

var hasIntersect = function (srcObj, targetObj) {

    if (!srcObj || !targetObj) {
        return false;
    }

    var keys = Object.keys(targetObj);

    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];

        if (UtilType.isDefined(srcObj[key]) &&
            UtilType.isDefined(targetObj[key]) &&
            srcObj[key] === targetObj[key]) {

            return true;
        }
    }

    return false;
};

var filterDocumentFields = function(doc, targetFieldNames) {

    if (!targetFieldNames || targetFieldNames.length === 0) {

        return doc;
    }

    var result = {};

    targetFieldNames.forEach(function(fieldName) {

        let val = lodashObject.get(doc, fieldName);
        lodashObject.set(result, fieldName, val);

    });

    return result;
};

const removeDisableSaveFieldValues = function(document, template) {
  
  if (template && template.components && template.components.length > 0) {
      for (let t = 0, len = template.components.length; t < len; t++) {
        const fld = template.components[t];
        if (fld.disableSave === true) {
          delete document[fld.name];
        }
      }
  }

};

module.exports = {
    isNew: isNew,

    isDeleted: isDeleted,

    isPreviousVersion: isPreviousVersion,

    hasIntersect: hasIntersect,

    filterDocumentFields: filterDocumentFields,

    removeDisableSaveFieldValues: removeDisableSaveFieldValues
};
