<?php

namespace Planaday\Config\OptionGroups\Course\General;

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

class GeneralOptionsValidator {
	use Logging;

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

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

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

	/**
	 * @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 algemene opties is met ongeldige data ingevuld.'
				);
			}

			$output = $errors;
			return false;
		}

		$output = $data;
		return true;
	}

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

		$string = [
			GeneralOptionsEnum::DAY_PART_TEXT
		];

		$bool = [
			GeneralOptionsEnum::INCLUDE_OPTION_IN_COUNT,
			GeneralOptionsEnum::SKIP_E_LEARNING_ONLY
		];

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

}