<?php

namespace Planaday\Config\OptionGroups\Course\Calendar;

use Planaday\Platform\PlatformAbstraction\LocalizationController;
use Planaday\Utility\DataFilters\AdvancedValidatorFactory;
use Planaday\Utility\DataFilters\InvalidFieldsException;
use Planaday\Utility\DataFilters\TypeValidator;
use Planaday\Utility\Debug\Log\Logging;

class CalendarOptionsValidator {
	use Logging;

	/** @var TypeValidator */
	protected $typeValidator;

	/** @var LocalizationController */
	protected $translator;

	/** @var AdvancedValidatorFactory */
	private $advancedValidator;

	public function __construct( TypeValidator $typeValidator, LocalizationController $translator, AdvancedValidatorFactory $advancedValidator) {
		$this->typeValidator            = $typeValidator;
		$this->translator               = $translator;
		$this->advancedValidator        = $advancedValidator;
	}

	/**
	 * @param array $data
	 * @param array|null $output if valid, clean data is returned here. if not, errors will be returned here
	 *
	 * @return bool true if valid, false if not
	 */
	public function validate( array $data, ?array &$output): bool {
		$errors = [];
		$tr = $this->translator;

		try {
			$data = $this->getSafeData( $data );
		} catch ( InvalidFieldsException $e ) {
			foreach ( $e->getInvalidFields() as $field => $fieldException ) {
				$this->logError('Invalid field: ' . $field . ' with error: ' . $fieldException->getMessage());
				$errors[ $field ] = $tr->translate(
					'Het ' . strtolower($field) . ' veld bij de kalender opties is met ongeldige data ingevuld.'
				);
			}

			$output = $errors;
			return false;
		}

		if(!$this->advancedValidator->isHexColor($data[CalendarOptionsEnum::BACKGROUND_COLOR] ?? null)){
			$errors[CalendarOptionsEnum::BACKGROUND_COLOR] = $tr->translate(
				'De achtergrond kleur moet een hex waarde zijn. Dit kan een hex waarde zijn van 3,4,6 of 8 karakters.'
			);
		}

		if(!$this->advancedValidator->isHexColor($data[CalendarOptionsEnum::TEXT_COLOR] ?? null)){
			$errors[CalendarOptionsEnum::TEXT_COLOR] = $tr->translate(
				'De text kleur moet een hex waarde zijn. Dit kan een hex waarde zijn van 3,4,6 of 8 karakters.'
			);
		}

		if ( count( $errors ) > 0 ) {
			$output = $errors;
			$this->logWarning("data is not valid", $errors);
			return false;
		}

		$output = $data;
		return true;
	}

	/**
	 * @param array $data
	 *
	 * @return array
	 * @throws InvalidFieldsException
	 */
	private function getSafeData(array $data): array {
		$tv = $this->typeValidator;

		$string = [
			CalendarOptionsEnum::BACKGROUND_COLOR,
			CalendarOptionsEnum::TEXT_COLOR
		];

		$bool = [
			CalendarOptionsEnum::SHOW_MOUSEOVER_TEXT,
			CalendarOptionsEnum::SHOW_ALL_DAY_PARTS
		];

		$int = [
			CalendarOptionsEnum::CALENDAR_VERSION
		];

		return $tv->getSafeData($data, $string, [], $bool, $int);
	}

}