# frozen_string_literal: true

require_relative 'abstract_handler'

module Hypertube
  module Core
    module Handler
      class CreateClassInstanceHandler < Hypertube::Core::Handler::AbstractHandler
        def initialize
          @required_parameters_count = 1
        end

        def process(command)
          create_class_instance(command)
        end

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

          if command.payload.length > 1
            constructor_arguments = command.payload[1..]
            class_instance = command.payload[0].send('new', *constructor_arguments)
          else
            class_instance = command.payload[0].send('new')
          end
          class_instance
        rescue NoMethodError
          methods = command.payload[0].methods
          message = "Method 'new' 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
