<?php
namespace Planaday\Html\Tags\Utility\CssConverter;

use Planaday\Html\Tags\Form\DataInputFieldTag;
use Planaday\Utility\CssClassAndIdConverter;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class CssConverter extends DataInputFieldTag {
	const TAG = 'css-converter';
	const DEFAULT_TEMPLATE = 'cssConverter';
	protected string $fieldName = 'pad-css-conversion-input';


	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct(Container $registry) {
		parent::__construct(__DIR__, self::DEFAULT_TEMPLATE, $registry);
	}

	public function buildTag(): string {
		$parser = $this->getNewParser();
		$parser->addStylesheet($this->getStylePath());
		$css = $this->getConversion();
		$parser->setUnsafeData('conversion', $css);
		$parser->setData('errors', substr_count($css, "pad-css-danger"));
		$parser->setData('changed', substr_count($css, "pad-css-good"));
		return $parser->parse($this->getTemplate());
	}

	protected function getConversion():string {
		$css = $this->getCurrentFieldValue();

		if ( !is_string($css) ){
			return '---';
		}

		$normalWrapper = function(string $oldClass, string $newClass){
			return "<span class='pad-css-replace-option pad-css-good' title='\"" . $oldClass . "\" => \"" .
			       $newClass. "\"' data-old='" . $oldClass . "'>" .
			       $newClass . '</span>';
		};

		$dangerWrapper = function(string $oldClass, string $newClass){
			return "<span class='pad-css-replace-option pad-css-danger' title='\"" . $oldClass . "\" => \"" .
			       $newClass. "\"' data-old='" . $oldClass . "'>" .
			       $oldClass . '</span>';
		};

		$converter = new CssClassAndIdConverter();
		$css = htmlspecialchars($css);
		$css = $converter->convertCss($css, $normalWrapper, $dangerWrapper, $dangerWrapper);
		$css = str_replace("\n", "<br>", $css);
		$css = str_replace("  ", "&nbsp; ", $css);
		return str_replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;", $css);
	}
}