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

module Contrast
  module Components
    # All components should inherit from this,
    # whether Interfaces, InstanceMethods or ClassMethods.
    module ComponentBase
      # use this to determine if the configuration value is literally boolean
      # false or some form of the word `false`, regardless of case. It should
      # be used for those values which default to `true` as they should only
      # treat a value explicitly set to `false` as such.
      #
      # @param config_param [Boolean,String] the value to check
      # @return [Boolean] should the value be treated as `false`
      def false? config_param
        return false if config_param == true
        return true if config_param == false
        return false unless config_param.cs__is_a?(String)

        config_param.downcase == Contrast::Utils::ObjectShare::FALSE
      end

      # use this to determine if the configuration value is literally boolean
      # true or some form of the word `true`, regardless of case. It should
      # be used for those values which default to `false` as they should only
      # treat a value explicitly set to `true` as such.
      #
      # @param config_param [Boolean,String] the value to check
      # @return [Boolean] should the value be treated as `true`
      def true? config_param
        return false if config_param == false
        return true if config_param == true
        return false unless config_param.cs__is_a?(String)

        config_param.downcase == Contrast::Utils::ObjectShare::TRUE
      end

      # this method will check if a path could be possibly used
      # So for example if we pass a path to a file - we'll check
      # if there is actually that file and if it's with certain extension
      #
      # @param config_path [String,nil]
      # @return [Boolean]
      def valid_cert? config_path
        return false if config_path.nil?

        exts = %w[.pem .crt .cer].cs__freeze
        return false unless exts.include?(File.extname(config_path))

        true
      end

      # check if file exists at all
      # @param path [String,nil]
      def file_exists? path
        return false unless path

        File.exist?(path)
      end
    end
  end
end