<?php

namespace Planaday\Platform\WordpressConfig\Widgets;

use Planaday\Config\FeatureToggles\FeatureToggleSettings;
use Planaday\Html\FeatureService;
use Planaday\Platform\PlatformAbstraction\UrlHandler;
use Planaday\Platform\WordpressConfig\Widgets\CourseDetails\CourseDetails;
use Planaday\Platform\WordpressConfig\Widgets\Search\Search;
use Planaday\Utility\Debug\Log\Logging;
use Planaday\Utility\Debug\PluginFeatureTimer;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\PluginData;

class WPWidgetService {
	use Logging;

	public function __construct(
		protected Container $container,
		protected PluginData $pluginData,
		protected UrlHandler $urlHandler,
		protected FeatureService $featureService,
		protected FeatureToggleSettings $featureToggleSettings,
		protected PluginFeatureTimer $timer
	) {}

	public function registerWidgets(): void{
		$stopLegacy = $this->timer->start("registering legacy widgets");
		$this->registerLegacyWidgets();
		$stopLegacy();
		$stopFeature = $this->timer->start("registering feature widgets");
		$this->registerFeatureWidgets();
		$stopFeature();
	}

	protected function registerFeatureWidgets(): static{
		foreach (WPWidgets::cases() as $block) {
			register_widget(new FeatureWidget(
				$block,
				$this->pluginData,
				$this->urlHandler,
				$this->container,
				$this->featureService,
				$this->featureToggleSettings
			));
		}

		return $this;
	}

	protected function registerLegacyWidgets(): static{
		try {
			register_widget($this->container->getInstance(CourseDetails::class));
		} catch (InjectionImpossibleException $e){
			$this->logError("Failed to create CourseDetails widget, error:" . $e->getMessage(), $e);
		}

		try {
			register_widget($this->container->getInstance(Search::class));
		} catch (InjectionImpossibleException $e){
			$this->logError("Failed to create Search widget, error:" . $e->getMessage(), $e);
		}

		return $this;
	}
}