# 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/api/decorators/instrumentation_mode'
require 'contrast/components/interface'
require 'contrast/utils/string_utils'

module Contrast
  module Api
    module Decorators
      # Used to decorate the ApplicationCreate protobuf model to handle reporting Agent process start
      module ApplicationStartup
        include Contrast::Components::ComponentBase
        include Contrast::Components::Interface
        access_component :config

        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
          #
          # @return [Contrast::Api::Dtm::ApplicationCreate]
          def build
            msg = new
            msg.app_version      = Contrast::Utils::StringUtils.protobuf_format CONFIG.root.application.version.to_s
            msg.code             = Contrast::Utils::StringUtils.protobuf_format CONFIG.root.application.code
            msg.group            = Contrast::Utils::StringUtils.protobuf_format CONFIG.root.application.group
            msg.metadata         = Contrast::Utils::StringUtils.protobuf_format CONFIG.root.application.metadata
            msg.mode             = Contrast::Api::Dtm::InstrumentationMode.build
            session!(msg)
            msg
          end

          private

          # Set the session metadata for this ApplicationCreate msg
          #
          # @param msg [Contrast::Api::Dtm::ApplicationCreate]
          def session! msg
            msg.session_id = Contrast::Utils::StringUtils.protobuf_format(
                CONFIG.root.application.session_id,
                truncate: false)
            msg.session_metadata = Contrast::Utils::StringUtils.protobuf_format(
                CONFIG.root.application.session_metadata,
                truncate: false)
          end
        end
      end
    end
  end
end

Contrast::Api::Dtm::ApplicationCreate.include(Contrast::Api::Decorators::ApplicationStartup)