<?php

namespace Planaday\Html\Tags\Course\Button;

use Planaday\Api\ApiException\InvalidResponseException;
use Planaday\Config\Course\Overview\OverviewSettings;
use Planaday\Entities\Course\CourseController;
use Planaday\Entities\Course\CourseUtility;
use Planaday\Entities\Course\Exception\CourseNotFoundException;
use Planaday\Html\Tags\InvalidAttributesException;
use Planaday\Html\Tags\Tag;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;

class CourseButton extends Tag {
	const TAG = 'legacy-course-button';

	const DEFAULT_TEMPLATE = 'button';
	const ID_ATTRIBUTE = 'data-id';
	protected CourseUtility $courseUtil;
	protected CourseController $courseController;
	protected OverviewSettings $overviewSettings;

	/**
	 * @param Container $registry
	 *
	 * @throws InjectionImpossibleException
	 */
	public function __construct( Container $registry ) {
		$this->courseController = $registry->getInstance( CourseController::class );
		$this->courseUtil = $registry->getInstance( CourseUtility::class );
		$this->overviewSettings = $registry->getInstance( OverviewSettings::class );
		parent::__construct( __DIR__, self::DEFAULT_TEMPLATE, $registry );
	}

	public function buildTag(): string {
		$parser = $this->getNewParser();

		try {
			$courseIdString = $this->attributes[self::ID_ATTRIBUTE] ?? null;
			if ($courseIdString === null) throw new InvalidAttributesException();

			$courseId = filter_var($courseIdString, FILTER_VALIDATE_INT);
			if ($courseId === false) throw new InvalidAttributesException();

			$course = $this->courseController->getCourse( $courseId );

			$parser->setUnsafeData('courseLink', $this->courseUtil->getDetailLink( $course ) );
			$parser->setData('buttonText', $this->overviewSettings->getCourseButtonText());

			return $parser->parse( $this->getTemplate() );
		} catch ( CourseNotFoundException ){
			$parser->setData('errorType', 'notFoundError');
		} catch ( InvalidResponseException ){
			$parser->setData('errorType', 'serverError');
		} catch ( InvalidAttributesException ){
			$parser->setData('errorType', 'attributeError');
		}

		return $parser->parse($this->getErrorTemplate());
	}
}