# frozen_string_literal: true

require_relative 'abstract_handler'
require_relative 'get_instance_field_handler'
require_relative '../../utils/command'
require_relative '../../utils/command_type'

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

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

          instance = command.payload[0]
          response_array = []
          response_array[0] = instance

          type_name = instance.nil? ? '' : instance.class.name
          response_array[1] = Hypertube::Utils::Command.new(command.runtime_name, Hypertube::Utils::CommandType::GET_TYPE, type_name)

          get_instance_field_handler = Hypertube::Core::Handler::GetInstanceFieldHandler.new
          (1...command.payload.length).each do |i|
            property_name = command.payload[i]
            property_value = get_instance_field_handler.process(
              Hypertube::Utils::Command.new(command.runtime_name, Hypertube::Utils::CommandType::GET_INSTANCE_FIELD, instance, property_name)
            )
            response_array[i + 1] = Hypertube::Utils::Command.new(
              command.runtime_name,
              Hypertube::Utils::CommandType::DTO_PROPERTY,
              property_name,
              property_value
            )
          end

          response_array
        end
      end
    end
  end
end
