<?php

namespace Internetgalerie\IgDatapoolFe\Property\TypeConverter;

use TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface;
use Internetgalerie\IgDatapoolFe\Controller\ActionController;
use TYPO3\CMS\Extbase\Property\Exception\InvalidPropertyMappingConfigurationException;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;

/**
 * This converter transforms arrays or strings to persistent objects. It does the following:
 *
 * - If the input is string, it is assumed to be a UID. Then, the object is fetched from persistence.
 * - If the input is array, we check if it has an identity property.
 *
 * - If the input has an identity property and NO additional properties, we fetch the object from persistence.
 * - If the input has an identity property AND additional properties, we fetch the object from persistence,
 *   and set the sub-properties. We only do this if the configuration option "CONFIGURATION_MODIFICATION_ALLOWED" is TRUE.
 * - If the input has NO identity property, but additional properties, we create a new object and return it.
 *   However, we only do this if the configuration option "CONFIGURATION_CREATION_ALLOWED" is TRUE.
 *
 * @api
 */
class PersistentObjectConverter extends \TYPO3\CMS\Extbase\Property\TypeConverter\PersistentObjectConverter
{

    protected $priority = 20;

    /**
     * Handle the case if $source is an array.
     *
     * @param  array                                                             $source
     * @param  string                                                            $targetType
     * @param  array                                                             &$convertedChildProperties
     * @param PropertyMappingConfigurationInterface $configuration
     * @return object
     * @throws InvalidPropertyMappingConfigurationException
     */
    public function convertFrom($source, string $targetType, array $convertedChildProperties = [], ?PropertyMappingConfigurationInterface $configuration = null): ObjectStorage
    {
        $object = parent::convertFrom($source, $targetType, $convertedChildProperties, $configuration);
        /**
         * First try session, then Persistence
         */
        $frontendUserAuthentication = $GLOBALS['TYPO3_REQUEST']->getAttribute('frontend.user');
        $sessObject = $frontendUserAuthentication->getKey('ses', md5(ActionController::$currentObjectClass));

        if ($sessObject != null) {
            foreach ($sessObject->_getProperties() as $name => $value) {
                if ($sessObject->_isDirty($name) && $sessObject->{'get'.ucfirst((string) $name)}() != null) {
                    $object->{'set'.ucfirst((string) $name)}($value);
                }
            }
        }

        return $object;
    }
}
