# frozen_string_literal: true

require_relative 'abstract_handler'

module Hypertube
  module Core
    module Handler
      class GetInstanceFieldHandler < Hypertube::Core::Handler::AbstractHandler
        def initialize
          @required_parameters_count = 2
        end

        def process(command)
          get_instance_field(command)
        end

        def get_instance_field(command)
          validate(command, @required_parameters_count, self.class.name)

          instance = command.payload[0]
          value = command.payload[1]
          if instance.instance_variable_defined?(value)
            response = instance.instance_variable_get(value)
          else
            fields = instance.instance_variables
            message = "Field #{command.payload[1]} not found in object of class #{instance.class.name}. Available fields:\n"
            fields.each { |field_iter| message += "#{field_iter}\n" }
            raise ArgumentError, message
          end
          response
        end
      end
    end
  end
end
