/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const { settings } = require('@contrast/protobuf-api');

const InventoryFeatures = require('./inventory-features');
const AssessFeatures = require('./assess-features');
const DefendFeatures = require('./defend-features');
const { wrapToObject } = require('../../helpers');
const {
  STRING_DEFINITION_TYPE,
  SYSLOG_CONNECTION_TYPES,
  SYSLOG_SEVERITIES
} = require('../../enums');

function ServerFeatures({
  assessment = {},
  defend = {},
  inventory = {},
  logFile,
  logLevel,
  useCache
} = {}) {
  return wrapToObject(
    new settings.ServerFeatures([
      useCache, //                           1                cache
      logFile, //                            2             log_file
      logLevel, //                           3            log_level
      InventoryFeatures(inventory).array, // 4            inventory
      AssessFeatures(assessment).array, //   5               assess
      DefendFeatures(defend).array, //       6               defend
      0 //                                   7 instrumentation_mode (0=UNDEFINED)
    ]),
    ServerFeatures.toObject
  );
}

ServerFeatures.toObject = ({
  defend: { ruleDefinitionsList, syslog } = {}
}) => {
  // Convert integer-valued enum fields to corresponding string values.
  if (ruleDefinitionsList) {
    ruleDefinitionsList.forEach(({ keywordsList, patternsList }) => {
      keywordsList.forEach((kw) => {
        kw.type = STRING_DEFINITION_TYPE[kw.type];
      });
      patternsList.forEach((p) => {
        p.type = STRING_DEFINITION_TYPE[p.type];
      });
    });
  }
  if (syslog) {
    syslog.connectionType = SYSLOG_CONNECTION_TYPES[syslog.connectionType];
    syslog.severityBlocked = SYSLOG_SEVERITIES[syslog.severityBlocked];
    syslog.severityExploited = SYSLOG_SEVERITIES[syslog.severityExploited];
    syslog.severityProbed = SYSLOG_SEVERITIES[syslog.severityProbed];
  }
};

module.exports = ServerFeatures;
