<?php

namespace Modules\Reports\AriaReports\Model;

abstract class ResponseAbstract
{

	protected \stdClass $object;

	protected ?string $textMessage = null;

	public function setObject(\stdClass $object): void
	{
		$this->object = $object;
		$this->checkObject();
		$this->processResponseObject();
	}

	protected function checkObject(): void
	{
		if (!$this->object->output) {
			throw new \RuntimeException('No output provided in the response body.');
		}
	}

	public function getTextMessage(): ?string
	{
		return $this->textMessage;
	}

	public function getObject(): \stdClass
	{
		return $this->object;
	}

	abstract protected function processResponseObject(): void;


	/**
	 * Returns the output part from the response; function has priority over message.
	 */
	protected function getRelevantOutput(): \stdClass
	{
		$functionCall = $message = null;

		foreach($this->object->output as $output) {
			if ($output->type=='function_call') {
				$functionCall = $output;
			} elseif ($output->type=='message') {
				$message = $output;
			}
		}

		if ($functionCall) {
			return $functionCall;
		} else {
			return $message;
		}

	}

}