# frozen_string_literal: true

require_relative 'abstract_handler'

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

        def process(command)
          invoke_instance_method(command)
        end

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

          instance = command.payload[0]
          method_name = command.payload[1]

          return instance.send(method_name) unless command.payload.length > 2

          arguments = command.payload[2..]
          instance.send(method_name, *arguments)
        rescue NoMethodError => e
          puts e.message
          methods = instance.methods
          message = "Method #{method_name} not found in object of class #{instance.class.name}. Available methods:\n"
          methods.each { |method_iter| message += "#{method_iter}\n" }
          raise Exception, message
        end
      end
    end
  end
end
