# frozen_string_literal: true

require_relative 'abstract_handler'

module Hypertube
  module Core
    module Handler
      class SetStaticFieldHandler < Hypertube::Core::Handler::AbstractHandler
        def initialize
          @required_parameters_count = 3
        end

        def process(command)
          Hypertube::Utils::Command.new(Hypertube::Utils::RuntimeNameHt::RUBY, Hypertube::Utils::CommandType::VALUE, [set_static_field(command)])
        end

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

          type = command.payload[0]
          field_name = command.payload[1]
          field_value = command.payload[2]

          type.class_variable_set(field_name, field_value)
          type
        rescue Exception
          fields = type.class_variables
          message = "Field #{command.payload[1]} not found in class #{type.name}. Available fields:\n"
          fields.each { |field_iter| message += "#{field_iter}\n" }
          raise ArgumentError, message
        end
      end
    end
  end
end
