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

module Contrast
  module Agent
    module Reporting
      module Settings
        # Helper methods used across the settings.
        module Helpers
          class << self
            # Fills instance variable [Array] with new settings as new instance type
            # for each entry.
            #
            # @param instance_type [Class] a class to create new instance from to
            # @param instance_variable [Array] instance variable accessor method
            # return an array to fill.
            # @param array [Array] array to be used to fill the iv.
            # fill the iv with the new type containing data from the provided array
            # param.
            # @return instance_variable [Class]
            def array_to_iv instance_type, instance_variable, array
              return unless array.is_a?(Array)

              array.each_with_index do |entry, index|
                new_instance = instance_type.new
                instance_type::ATTRIBUTES.each do |attr|
                  new_instance.send("#{ attr }=".to_sym, entry[no_more_underscore(attr)])
                end
                instance_variable[index] = new_instance
              end

              instance_variable
            end

            # :attr_name => :attrName
            # return original if no '_'
            #
            # @param attr_name [Symbol]
            # @return normalized_name [Symbol]
            def no_more_underscore attr_name
              name = attr_name.to_s
              idx = name.index('_')
              return attr_name if idx.nil? || (idx.zero? && idx >= name.length)

              result = name
              result.slice!(idx)
              result.insert(idx, name[idx]&.upcase)
              result.slice!(idx + 1)
              result.index('_') ? no_more_underscore(result).to_sym : result.to_sym
            end
          end
        end
      end
    end
  end
end