<?php

namespace App\Service;

use Pimcore\Model\DataObject\ClassDefinition\DynamicOptionsProvider\SelectOptionsProviderInterface;
use Pimcore\Bundle\ApplicationLoggerBundle\ApplicationLogger;
use Pimcore\Model\DataObject\ClassDefinition\Data;
use Pimcore\Model\DataObject\ClassDefinition\Data\Select;
use Pimcore\Translation\Translator;

class OptionsProvider implements SelectOptionsProviderInterface
{
	/**
	 * Component name for the application logger interface.
	 */
	const APPLICATION_LOGGER_COMPONENT_NAME = 'OptionsProvider';
	/**
	 * Related error messages used for exceptions.
	 */
	const ERROR_UNSUPPORTED_FIELD_NAME = 'error_unsupported_field_name';

	/**
	 * Pimcore Application Logger.
	 *
	 * @link https://pimcore.com/docs/6.x/Development_Documentation/Tools_and_Features/Application_Logger.html
	 * @var ApplicationLogger
	 */
	protected $applicationLogger;

	/**
	 * Pimcore translator service.
	 *
	 * @var Translator
	 * @link https://pimcore.com/docs/pimcore/current/Development_Documentation/Multi_Language_i18n/Shared_Translations.html
	 */
	protected $translator;

	/**
	 * @var UserService
	 */
	protected $userService;

	public function __construct(ApplicationLogger $applicationLogger, Translator $translator) {
		$this->applicationLogger = $applicationLogger;
		$this->translator = $translator;
	}

	public function getOptions(array $context, Data $fieldDefinition): array
	{
		$object = array_key_exists('object', $context) ? $context['object'] : null;
		$fullClassName = $object ? get_class($object) : '';
		switch ($fieldname = $context['fieldname']) {
			default:
				$errorMessage = $this->translator->trans(self::ERROR_UNSUPPORTED_FIELD_NAME, [
					$fieldname,
				]);
				$this->applicationLogger->error($errorMessage, [
					'component' => self::APPLICATION_LOGGER_COMPONENT_NAME,
				]);
				break;
		}

		return [];
	}

	public function hasStaticOptions(array $context, Data $fieldDefinition): bool
	{
		return true;
	}


	public function getDefaultValue(array $context, Data $fieldDefinition): ?string
    {
        return $fieldDefinition instanceof Select ? $fieldDefinition->getDefaultValue() : '';
    }

	/**
	 * Maps objects to array with options for admin selects
	 *
	 */
	private function objectsToOptions(array $objects, string $language): array
	{
		$options = [];
		foreach($objects as $object) {
			$options[] = ['key' => $object->getName($language), 'value' => (string)$object->getId()];
		}
		return $options;
	}

	/**
	 * Maps simple key-value array to options array in format for admin selects
	 *
	 */
	private function arrayToOptions(array $array, string $language): array
	{
		$options = [];
		foreach($array as $key => $item) {
			$options[] = ['key' => $item, 'value' => (string)$key];
		}
		return $options;
	}
}
