# frozen_string_literal: true

require_relative '../../utils/command_type'
require_relative '../../utils/command'
require_relative 'handler_dictionary'

module Hypertube
  module Core
    module Handler
      class AbstractHandler
        def process(_command)
          raise 'process is not implemented'
        end

        def handle_command(command)
          iterate(command) unless command.command_type == Hypertube::Utils::CommandType::OPTIMIZE
          process(command)
        end

        def validate(command, required_parameters_count, caller_type_name)
          raise ArgumentError, "#{caller_type_name} parameters mismatch" if command.payload.length < required_parameters_count
        end

        private

        def iterate(command)
          (0...command.payload.length).each do |i|
            next unless command.payload[i].is_a?(Hypertube::Utils::Command)

            inner_command = command.payload[i]
            command.payload[i] = $handler_dict[inner_command.command_type].handle_command(inner_command)
          end
        end
      end
    end
  end
end
