<?php

namespace Planaday\Platform\WordpressConfig\Widgets;

use Exception;
use Planaday\Config\FeatureToggles\FeatureToggleSettings;
use Planaday\Html\FeatureService;
use Planaday\Html\Nodes\NodeData;
use Planaday\Html\Parsers\ParseFailedException;
use Planaday\Html\Parsers\StdDOMParser;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\FormBuilder\DataTypes\StringType;
use Planaday\Utility\FormBuilder\Form;
use Planaday\Utility\FormBuilder\InputFields\SelectionInput;
use Planaday\Utility\FormBuilder\Structures\RemotelyLoadedForm;
use Planaday\Utility\PluginData;
use WP_Widget;

class FeatureWidget extends WP_Widget{
	public function __construct(
		protected WPWidgets $block,
		protected PluginData $pluginData,
		protected UrlHandler $urlHandler,
		protected Container $container,
		protected FeatureService $featureService,
		protected FeatureToggleSettings $featureToggleSettings
	){
		parent::__construct(
			$pluginData->getFullPrefix() . '-feature-widget-' . $block->value,
			$pluginData->getFullPrefix(). ' block: ' . $block->getTitle(),
			array(
				'customize_selective_refresh' => true,
				'description' => $block->getDescription()
			)
		);
	}

	public function widget( $args, $instance ): void {
		try {
			$hash = md5(serialize($instance));

			echo $this->featureService->getParsed( $this->block->getClass(), [ ...$instance, "widget_hash" => $hash]);

			set_transient( $this->pluginData->getShortPrefix() . '-hash-' . $hash, $instance, 60 * 60 * 24);
		} catch ( Exception $e ) {
			echo "<div> Iets is niet goed gegaan, probeer het later opnieuw: {$e->getMessage()}</div>";
		}
	}

	protected function updateConfigArrayLayer(array $configArrayLayer, array $valuesArray): array {
		foreach ($valuesArray as $key => $value) {
			if (is_array($value)) {
				$configArrayLayer[$key] = $this->updateConfigArrayLayer($configArrayLayer[$key] ?? [], $value);
			} else {
				$configArrayLayer[$key] = $value;
			}
		}

		return $configArrayLayer;
	}

	public function update( $new_instance, $old_instance ): array {
		if (isset($new_instance["dataJson"])) $newInstanceData = json_decode($new_instance['dataJson'], true);
		return $this->updateConfigArrayLayer($old_instance, $newInstanceData ?? []);
	}

	public function form( $instance ): void {
		try {
			$parser = $this->container->getInstanceTransient( StdDOMParser::class );
		} catch ( InjectionImpossibleException $e ) {
			echo "<div> Iets is niet goed gegaan, probeer het later opnieuw: {$e->getMessage()} </div>";
			return;
		}

		$templates = $this->block->getClass()::getAllowedTemplates($this->featureToggleSettings);
		$templateOptions = [];
		foreach ($templates as $templateName => $template) {
			$templateOptions[] = [
				'value' => $template,
				'label' => $templateName
			];
		}

		$form = (new Form())->forceDivElement()->outputJsonToHiddenField()->setName( 'feature-widget' )->setIndex(substr($this->get_field_name(""), 0, -2))->addContents(
			$template = (new SelectionInput( new StringType() ))
				->setName( 'template' )
				->setIndex( 'template' )
				->setOptions( $templateOptions )
				->setDefaultValue( $instance['template'] ?? $templates[0] ),
			(new RemotelyLoadedForm())
				->setIndex('config' )
				->setUrl( $this->urlHandler->getBaseUrl() . '/wp-json/' . $this->pluginData->getFullPrefix() . '/v1/wordpress-blocks/render/' . $this->block->value )
				->addDependencies( $template )
		);

		$parser->preloadData(new NodeData(['formJson' => json_encode($form), 'formData' => json_encode($instance), 'autoGenerated' => ['lastValidDir' => __DIR__]]));
		try{
			echo $parser->parse( file_get_contents( __DIR__ . '/widgetSettingsTemplate.html' ));
		} catch (ParseFailedException $e) {
			echo "<div> Iets is niet goed gegaan, probeer het later opnieuw: {$e->getMessage()}</div>";
		}
	}


}