# frozen_string_literal: true

require_relative 'abstract_handler'

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

        def process(command)
          invoke_static_method(command)
        end

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

          type = command.payload[0]
          method_name = command.payload[1]
          if command.payload.length > @required_parameters_count
            args = command.payload[2..]
            result = type.send(method_name, *args)
          else
            result = type.send(method_name)
          end
          result
        rescue NoMethodError
          methods = command.payload[0].methods
          message = "Method #{method_name} not found in class #{command.payload[0].name}. Available methods:\n"
          methods.each { |method_iter| message += "#{method_iter}\n" }
          raise Exception, message
        end
      end
    end
  end
end
