# frozen_string_literal: true

require_relative 'abstract_handler'

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

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

          if command.payload[0].is_a? Array
            get_item_array(command)
          elsif command.payload[0].is_a? Hash
            get_item_hash(command)
          else
            raise ArgumentError.new format('Cannot get element from %s', command.payload[0])
          end
        end

        def get_item_array(command)
          array = command.payload[0]
          indexes = if command.payload[1].is_a? Array
                      command.payload[1]
                    else
                      command.payload[1..]
                    end

          return unless array.is_a? Array

          indexes.each do |i|
            array = array[i]
          end
          array
        end

        def get_item_hash(command)
          hash = command.payload[0]
          key = command.payload[1]
          hash[key]
        end
      end
    end
  end
end
