<?php

namespace Planaday\Config\OptionGroups\Course\Search;

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

class SearchOptionsValidator {
	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 search 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;

		$int = [
			SearchOptionsEnum::OUTPUT_FORMAT
		];

		$bool = [
			SearchOptionsEnum::ASK_TITLE,
			SearchOptionsEnum::ASK_LOCATION,
			SearchOptionsEnum::ASK_LABELS,
			SearchOptionsEnum::ASK_CODE_95,
			SearchOptionsEnum::ASK_SOOB,
			SearchOptionsEnum::ASK_E_LEARNING,
			SearchOptionsEnum::ASK_STAP,
		];

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

}