# frozen_string_literal: true

require_relative 'abstract_handler'

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

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

          data = command.payload[0]
          if data.is_a? Array
            set_item_array(command)
          elsif data.is_a? Hash
            set_item_hash(command)
          else
            raise ArgumentError.new format('Cannot set element of %s', data)
          end
          data
        end

        def set_item_array(command)
          array = command.payload[0]
          value = command.payload[2]
          indexes = if command.payload[1].is_a? Array
                      command.payload[1]
                    else
                      [command.payload[1]]
                    end
          indexes[..-2].each do |i|
            array = array[i]
          end
          array[indexes[-1]] = value
        end

        def set_item_hash(command)
          hash = command.payload[0]
          key = command.payload[1]
          value = command.payload[2]
          hash[key] = value
        end
      end
    end
  end
end
