<?php
namespace App\Utils\Views;

class JSONExplorer extends \App\Utils\Views\AbstractHtmlComponent
{
	/**
	 * The json object
	 *
	 * @var \stdClass
	 */
	protected $json = null;

	/**
	 * Internal object id, used in js
	 *
	 * @var string
	 */
	protected $ID = null;

	/**
	 * Create a new JSON viewer
	 */
	public function __construct(\stdClass $json)
	{
		$this->json = $json;
	}

	/**
	 * Get the current ID
	 */
	private function getId()
	{
		if ($this->ID) {
			return $this->ID;
		}
		$this->ID = 'JsonExplorer_' . md5(mt_rand());
		return $this->ID;
	}

	/**
	 * Render the JSON only.
	 * Usually called from the template
	 * @return string
	 */
	public function renderHtml()
	{
		$output = "";
		$output.= sprintf("<div class='JSONExplorer %s %s' id=%s>", ($this->getOption('easySelect') ? 'select-easy' : ''), ($this->getOption('noSelect') ? 'select-none' : ''), $this->getId());

		$replacements = [
			// strings
			'/("[^\"]*")[\s]*:[\s]*("[^"]*")/' => '<span class="key">$1</span>: <span class="value value-string">$2</span>',

			// bool
			'/("[^\"]*")[\s]*:[\s]*(true)/' => '<span class="key">$1</span>: <span class="value value-bool true">$2</span>',
			'/("[^\"]*")[\s]*:[\s]*(false)/' => '<span class="key">$1</span>: <span class="value value-bool false">$2</span>',

			// numbers
			'/("[^\"]*")[\s]*:[\s]*([-]*[0-9.]+)/' => '<span class="key">$1</span>: <span class="value value-number">$2</span>',

			// null
			'/("[^\"]*")[\s]*:[\s]*(null)/' => '<span class="key">$1</span>: <span class="value value-null">$2</span>',

			// object
			'/("[^\"]*")[\s]*:[\s]*({)/' => '<span class="key key-parent">$1</span>: {',
		];

		$output.= preg_replace(array_keys($replacements), array_values($replacements), json_encode($this->json, JSON_HEX_QUOT | JSON_PRETTY_PRINT | JSON_FORCE_OBJECT));
		$output.= sprintf("</div>");

		return $output;
	}


	public function renderJs(\Engine\Theme\JSLoader\LoaderAbstract $JSLoader)
	{
		return '';
	}

	public function preloadCss(\Engine\Theme\CSSLoader\Complex $CSSLoader)
	{
		$CSSLoader->loadGroup("utils.views.jsonexplorer");
		return '';
	}

	public function preloadJs(\Engine\Theme\JSLoader\LoaderAbstract $JSLoader)
	{
		$JSLoader->loadGroup("utils.views.jsonexplorer");
		return '';
	}

}
