<?php

namespace Planaday\Html\Tags\Test\FunctionTestTag;

use Exception;
use Planaday\Html\Tags\Tag;
use Planaday\Utility\DataFilters\InvalidFieldsException;
use Planaday\Utility\Debug\ObjectToArrayConverter;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class FunctionTestTag extends Tag {
	const TAG = 'function-test';
	const DEFAULT_TEMPLATE = 'functionTestTag';

	protected ObjectToArrayConverter $objectToArrayConverter;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct( Container $registry ) {
		$this->objectToArrayConverter = $registry->getInstance(ObjectToArrayConverter::class);
		parent::__construct(__DIR__, self::DEFAULT_TEMPLATE, $registry);
		$this->logInfo('function test tag constructed');
	}

	public function buildTag(): string {
		$this->logInfo('function test tag building');
		$parser = $this->getNewParser();
		$parser->addStylesheet($this->getStylePath());

		try {
			$apiResponse = [];

			$this->logError('test error', 'testData');
			$this->logWarning('test warning', 'testData');
			$this->logInfo('test info', 'testData');
			$this->logDebug('test debug', 'testData');
		} catch ( Exception $e){
			$apiResponse = $this->buildDataArray($e);
		}

		$parser->setUnsafeData('apiCallReturnData', $this->buildDataArray($apiResponse));

		return $parser->parse($this->getTemplate());
	}

	/**
	 * @param mixed $array
	 *
	 * @return string
	 */
	private function buildDataArray(mixed $array): string{
		$output = '';

		if (is_object($array) && !$array instanceof Exception){
			$array = $this->objectToArrayConverter->convert($array);
		}

		if ($array instanceof Exception) return '<div class="pad-dataItem">' . $array->getMessage() . '</div>';

		if (!is_array($array)) return '<div class="pad-keyItem"> returned value </div> <div class="pad-dataItem">' . htmlspecialchars(print_r($array, true)) . '</div>';

		foreach ($array as $key => $value){
			if ($value === '') $value = 'EMPTY STRING';

			$output .= '<div class="pad-keyItem">' . htmlspecialchars($key) . htmlspecialchars(is_object($value)?'(' . str_replace('\\', "\\ ",get_class($value)) . ')':'') . '</div>';

			if (is_array($value) || (is_object($value) && !$value instanceof Exception)){
				$value = $this->buildDataArray($value);
				$output .= '<div class="pad-dataItem pad-array">' . $value . '</div>';
			} elseif ($value instanceof InvalidFieldsException){
				$value = $this->buildDataArray($value->getAllMessagesLayered());
				$output .= '<div class="pad-dataItem pad-array">' . $value . '</div>';
			} elseif ($value instanceof Exception){
				$output .= '<div class="pad-dataItem">' . $value->getMessage() . '</div>';
			} else {
				$output .= '<div class="pad-dataItem">' . htmlspecialchars(print_r(is_bool($value) ? ($value ? "TRUE" : "FALSE") : $value, true)) . '</div>';
			}
		}

		return $output;
	}
}