<?php

namespace StevenBuehner\sbChurchtoolsGrouphomepage\Controller;

use StevenBuehner\sbChurchtoolsGrouphomepage\Always\MyContainer;
use StevenBuehner\sbChurchtoolsGrouphomepage\Controller\AbstractController;
use StevenBuehner\sbChurchtoolsGrouphomepage\Helper\ArrayHelper;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Exceptions\InvalidArgumentException;
use StevenBuehner\sbChurchtoolsGrouphomepage\Service\Models\Event;

class CountdownFrontendController extends AbstractController {

	protected function init(): void {

		$this->setUpHooks(
			FALSE,
			FALSE,
			FALSE,
			TRUE,
			FALSE,
			TRUE,
			TRUE
		);

		$this->domain = 'sb-ct-blocks';

	}


	public function registerGutenbergBlocksAndCategories() {
		parent::registerGutenbergBlocksAndCategories();

		// Domain: sb-ct-blocks
		// Handle: sb-churchtools-countdown-editor-script
		// WordPress will check for a file in that path with the format ${domain}-${locale}-${handle}.json as the source of translations.
		$this->registerBlockJson(__DIR__ . '/../../build/Countdown', TRUE, TRUE);

	}


	public function render($attributes = [], $content = '') {

		try {
			/** @var Event $event */
			$event = $this->loadFilteredEventFromCalendar($attributes['calendar'], $attributes['titleRegExp'], $attributes['descriptionRegExp']);
		} catch (\Exception $e) {
			return $content;
		}

		$keysToExtract   = ['title', 'start', 'end', 'url'];
		$eventAttributes = ArrayHelper::extractKeys($event->__toArray(), $keysToExtract);
		$componentProps  = ArrayHelper::extractKeys($attributes, ['design', 'link_to', 'static_url', 'color_font', 'headline_format']);

		$componentProps['class'] = 'sb-block-churchtools-countdown';

		return $this->modifyHtmlElement($content, array_merge($eventAttributes, $componentProps));


	}



	/**
	 * @param $calendarId
	 * @param $titleRegExp
	 * @param $descriptionRegExp
	 * @return Event
	 * @throws \Exception
	 */
	protected function loadFilteredEventFromCalendar($calendarId, $titleRegExp = NULL, $descriptionRegExp = NULL) {

		if (empty($calendarId)) {
			throw new InvalidArgumentException(__('Missing Calendar', $this->domain));
		}

		$calService = MyContainer::getCtCalendarService();
		$clearCache = FALSE; // is_admin(); // Für eingeloggte Benutzer
		$events     = $calService->getFilteredEventsFromCalendar($calendarId, 1, $titleRegExp, $descriptionRegExp, NULL, $clearCache);
		$hasEvent   = count($events) > 0;

		if ($hasEvent) {
			return $events[0];
		}

		throw new InvalidArgumentException(__('No events found', $this->domain));

	}

}
