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

require 'contrast/components/logger'
require 'contrast/agent/reporting/reporting_events/application_reporting_event'
require 'contrast/agent/reporting/reporting_events/architecture_component'
require 'contrast/utils/object_share'

module Contrast
  module Agent
    module Reporting
      # This is the new ApplicationInventoryActivity class which will include all the information
      # about the inventory of the application which was discovered during exercise of the application
      # during this activity period.
      class ApplicationInventoryActivity < Contrast::Agent::Reporting::ApplicationReportingEvent
        # return [Array<Contrast::Agent::Reporting::ArchitectureComponent>]
        attr_reader :components
        # @ return [Array<String>] - User-Agent Header value
        attr_reader :browsers

        def initialize
          @event_type = :application_inventory_activity
          @browsers = []
          @components = []
          super()
        end

        def to_controlled_hash
          {
              activityDuration: duration,
              browsers: browsers,
              components: components.map(&:to_controlled_hash)
          }
        end

        # @param architectures [Array<Contrast::Agent::Reporting::ArchitectureComponent>,
        #   Contrast::Agent::Reporting::ArchitectureComponent]
        def attach_data architectures
          Array(architectures).each do |architecture|
            @components << architecture
          end
          request_headers = Contrast::Agent::REQUEST_TRACKER.current&.request&.headers
          @browsers << request_headers['USER_AGENT'] if request_headers
        end

        def duration
          Contrast::Utils::Timer.now_ms - (Contrast::Agent::REQUEST_TRACKER.current&.timer&.start_ms || 0)
        end

        # Helper method to determine if InventoryActivity has no data
        def empty?
          @browsers.empty? && @components.empty?
        end
      end
    end
  end
end