# Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

require 'contrast/api/dtm.pb'
require 'contrast/utils/string_utils'
require 'contrast/components/base'

module Contrast
  module Api
    module Decorators
      # Used to decorate the AgentStartup protobuf model to handle reporting Agent process start
      module AgentStartup
        include Contrast::Components::ComponentBase

        def self.included klass
          klass.extend(ClassMethods)
        end

        # Used to add class methods to the AgentStartup class on inclusion of the decorator
        module ClassMethods
          # Return a new DTM with the values from the configuration and Agent discovery
          #
          # @parma name [String] the Hostname of this Server, or overridden value, used to identify this process
          # @parma name [String] the Hostname of this Server, or overridden value, used to identify this process
          # @parma name [String] the Hostname of this Server, or overridden value, used to identify this process
          # @return [Contrast::Api::Dtm::AgentStartup]
          def build name, path, type
            msg = new
            msg.server_version   = Contrast::Agent::VERSION
            msg.server_name      = Contrast::Utils::StringUtils.protobuf_format name
            msg.server_path      = Contrast::Utils::StringUtils.protobuf_format path
            msg.server_type      = Contrast::Utils::StringUtils.protobuf_format type
            config!(msg)
            msg.finding_tags = Contrast::Utils::StringUtils.protobuf_format ::Contrast::ASSESS.tags
            msg
          end

          private

          # set the configuration driven values for this AgentStartup msg
          #
          # @param msg [Contrast::Api::Dtm::AgentStartup]
          def config! msg
            msg.version          = Contrast::Utils::StringUtils.protobuf_format ::Contrast::CONFIG.root.server.version
            msg.environment      = Contrast::Utils::StringUtils.protobuf_format ::Contrast::CONFIG.root.server.environment
            msg.server_tags      = Contrast::Utils::StringUtils.protobuf_format ::Contrast::CONFIG.root.server.tags
            msg.application_tags = Contrast::Utils::StringUtils.protobuf_format ::Contrast::CONFIG.root.application.tags
            msg.library_tags     = Contrast::Utils::StringUtils.protobuf_format ::Contrast::CONFIG.root.inventory.tags
          end
        end
      end
    end
  end
end

Contrast::Api::Dtm::AgentStartup.include(Contrast::Api::Decorators::AgentStartup)