<?php

namespace Internetgalerie\IgDatapoolFe\Property\TypeConverter;

//use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\StringUtility;
use TYPO3\CMS\Extbase\Domain\Model\FileReference;
use TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface;
use TYPO3\CMS\Extbase\Property\TypeConverter\AbstractTypeConverter;

/**
 * Class FileReferenceConverter
 */
class FileReferenceConverter extends AbstractTypeConverter
{
    protected $debug = false;
    protected $debugLog='/tmp/log2.txt';

    /**
     * @var array<string>
     */
    protected $sourceTypes = [ 'array' ];

    /**
     * @var string
     */
    protected $targetType = FileReference::class;

    /**
     * Needs to take precedence over the available FileReferenceConverter (also the one from sf_register in UploadedFileReferenceConverter.php)
     *
     * @var integer
     */
    protected $priority = 32;

    /**
     * @var \TYPO3\CMS\Core\Resource\ResourceFactory
     */
    protected $resourceFactory;

    /**
     * @var \TYPO3\CMS\Extbase\Security\Cryptography\HashService
     */
    protected $hashService;

    /**
     * @var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager
     */
    protected $persistenceManager;

    /**
     * @var \TYPO3\CMS\Core\Resource\FileInterface[]
     */
    protected $convertedResources = array();

    /**
     * @var \Internetgalerie\IgDatapoolFe\Domain\Repository\FileReferenceRepository
     */
    protected $fileReferenceRepository = null;


    /**
     * @var \Internetgalerie\IgDatapoolFe\Utility\FormUtility
     */
    protected $formUtility;


    protected $fileFactory;

    public function injectFileFactory(\TYPO3\CMS\Core\Resource\ResourceFactory $fileFactory)
    {
        $this->fileFactory = $fileFactory;
    }



    public function __construct()
    {
        $this->resourceFactory = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\ResourceFactory::class);
        $this->hashService = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Security\Cryptography\HashService::class);
        $this->fileReferenceRepository = GeneralUtility::makeInstance(\Internetgalerie\IgDatapoolFe\Domain\Repository\FileReferenceRepository::class);
        $this->persistenceManager = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
        $this->formUtility = GeneralUtility::makeInstance(\Internetgalerie\IgDatapoolFe\Utility\FormUtility::class);
    }

    public function log($text)
    {
        $fp = fopen($this->debugLog, 'a');
        fputs($fp, $text ."\n");
        fclose($fp);
    }
    public function log_var_dump($var)
    {
        $fp = fopen($this->debugLog, 'a');
        //ob_start();      var_dump($var);      $text = ob_get_clean();
        $text = var_export($var, true);
        fputs($fp, 'File-DUMP[FileReferenceConverter]=' .  $text ."\n");
        fclose($fp);
    }


    /*
     *  nicht bei Extension SYSEXT: from konvertieren
     * @todo verbessern - nur bei vorhanden sein von __dpInlineFields und __dpUploadFal und __dpUploadFileReferences
     */
    public function canConvertFrom($source, string $targetType): bool
    {
        foreach ($_POST as $name=>$val) {
            if ($name == 'tx_form_formframework') {
                return false;
            }
        }
        if ($this->debug) {
            $this->log('canConvertFrom FileReferenceConverter');
        }
        return true;
    }
    /**
     * Actually convert from $source to $targetType, taking into account the fully
     * built $convertedChildProperties and $configuration.
     *
     * @param  string|integer                                                    $source
     * @param  string                                                            $targetType
     * @param  array                                                             $convertedChildProperties
     * @param  \TYPO3\CMS\Extbase\Property\PropertyMappingConfigurationInterface $configuration
     * @throws \TYPO3\CMS\Extbase\Property\Exception
     * @return \TYPO3\CMS\Extbase\Domain\Model\AbstractFileFolder
     * @api
     */
    public function convertFrom($source, string $targetType, array $convertedChildProperties = array(), PropertyMappingConfigurationInterface $configuration = null): ?FileReference
    {
        /*
         * If we already converted it..
         */
        if ($this->debug) {
            $this->log("\n-----------------------------------------------------\nINIT: FileReferenceConverter.php");
        }
        if (isset($this->convertedResources[md5(serialize($source))])) {
            return $this->convertedResources[md5(serialize($source))];
        }

        /**
         * OK, for my understanding..
         * we have 2 kinds of references:
         * MODEL --> TYPO3\\CMS\\Extbase\\Domain\\Model\\FileReference --> TYPO3\CMS\Core\Resource\FileReference  --> TYPO3\CMS\Core\Resource\File
         */

        $fileReference = null;
        $fileReferenceUid = null;

        if ($this->debug) {
            $this->log_var_dump($source);
        }
        if (isset($source['__identity'])) {
            $fileReferenceUid =intval($source['__identity']);//$this->hashService->validateAndStripHmac($val);// intval($val);
            if ($this->debug) {
                $this->log('__identity='. $fileReferenceUid);
            }
            if ($fileReferenceUid > 0) {
                $fileReference = $this->fileReferenceRepository->findByUid($fileReferenceUid);
                if ($fileReference === null) {
                    // File Reference existiert in DB nicht mehr -> wird geloescht da null
                    if ($this->debug) {
                        $this->log('found fileReference['.$fileReferenceUid.'] NOT FOUND');
                    }
                } else {
                    if ($this->debug) {
                        $this->log('found fileReference['.$fileReferenceUid.'] uid='.$fileReference->getUid());
                    }
                }
            }
        }

        if (isset($source['uidLocal'])) {
            $fileSource=$source['uidLocal']; //$source['uidLocal']
            if ($this->debug) {
                $this->log('found uidLocal by'. $fileReferenceUid);
            }
        }

        if ($this->debug) {
            $this->log('IN :'. $fileReferenceUid);
        }

        /*
        if( isset($fileSource['mode']) ) {
          $fr_mode = $this->hashService->validateAndStripHmac($fileSource['mode']);
        } else {
          $fr_mode ='sys_file_reference';
        }
        $this->log('uid=' . $fileReferenceUid . ', fr_mode='.$fr_mode. ', fr_delete_uid='.$fileReferenceUid  );
        */

        // FileReferenze von bestehendem File erzeugen
        if (isset($fileSource['langFile']) && $fileSource['langFile']!='') {
            //$this->log('langFile='. $fileSource['langFile'] );
            $langFileId = intval($this->hashService->validateAndStripHmac($fileSource['langFile']));
            if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($langFileId)
                && $langFileId>0
            ) {
                //($source['description']!='' || $source['title']!='') ) {
                // Here we have a reference ID.. so do nothing, basically ^^
                // make sure no one has tempered with it.
                //$this->log('langFile: canBeInterpretedAsInteger');


                $fileReference = $this->formUtility->createFileReferenceFromFalUid($langFileId);
            }
        } else {
            // delete fileReference
            if ($this->debug) {
                $this->log('delete???? fileReferenceUid='. $fileReferenceUid .' und remove='.$fileSource['remove']);
            }
            if ($fileReferenceUid>0 && (int)$fileSource['remove']==1) {
                // Delete reference
                if (is_object($fileReference)) {
                    if ($this->debug) {
                        $this->log('DELETE fileReference uid=' . $fileReference->getUid());
                    }
                    $this->fileReferenceRepository->remove($fileReference);
                }
                $fileReference=null;
            }

            // Neues File
            if (isset($fileSource['newFile']) && $fileSource['newFile']!='') {
                $options = $this->hashService->validateAndStripHmac($fileSource['options']);
                $options = unserialize(base64_decode($options));
                $fileReference = $this->formUtility->createFileReference($fileSource['newFile'], $fileSource['origFilename'], $options, $configuration);
                if ($this->debug) {
                    $this->log('New fileReference uid=' . $fileReference->getUid());
                }
            }

            // Filereference from existing file
            if (isset($fileSource['newFileUid']) && (int)$fileSource['newFileUid'] > 0) {
                $options = $this->hashService->validateAndStripHmac($fileSource['options']);
                $options = unserialize(base64_decode($options));
                $fileReference = $this->resourceFactory->createFileReferenceObject(
                    [
                        'uid_local' => (int) $fileSource['newFileUid'], //$file->getUid(),
                        'uid_foreign' => StringUtility::getUniqueId('NEW_'),
                        'uid' => StringUtility::getUniqueId('NEW_'),
                        'crop' => null,
                    ]
                );
                $fileReference = $this->formUtility->createFileReferenceModelFromResource($fileReference);
                if ($this->debug) {
                    $this->log('New fileReference from file uid=' . $fileReference->getUid());
                }
            }

            // Filereference from existing file
            if (isset($fileSource['curFile']) && $fileSource['curFile'] !== '') {
                $options = $this->hashService->validateAndStripHmac($fileSource['options']);
                $options = unserialize(base64_decode($options));
                $fileUid = (int)$this->hashService->validateAndStripHmac($fileSource['curFile']);

                if($fileUid > 0) {
                    $fileReference = $this->resourceFactory->createFileReferenceObject(
                        [
                            'uid_local' => $fileUid, //$file->getUid(),
                            'uid_foreign' => StringUtility::getUniqueId('NEW_'),
                            'uid' => StringUtility::getUniqueId('NEW_'),
                            'crop' => null,
                        ]
                    );
                    $fileReference = $this->formUtility->createFileReferenceModelFromResource($fileReference);
                    if ($this->debug) {
                        $this->log('New fileReference from file uid=' . $fileReference->getUid());
                    }
                }
            }
        }

        if ($fileReference) {
            if (isset($source['title'])) {
                $fileReference->setTitle($source['title']);
                if ($this->debug) {
                    $this->log('fileReference set title :'. $source['title']);
                }
            }
            if (isset($source['description'])) {
                $fileReference->setDescription($source['description']);
            }
            if (isset($source['sortingForeign'])) {
                $fileReference->setSortingForeign($source['sortingForeign']);
            }
            if (isset($source['_languageUid'])) {
                $fileReference->set_languageUid($source['_languageUid']);
            }

            if ($this->debug) {
                $this->log('return FileReference');
            }

            return $fileReference;
        }

        if ($this->debug) {
            $this->log('return FileReference=NULL');
        }
        return null;
    }
    /**
     * Returns the source, if it is an array, otherwise an empty array.
     *
     * @param  mixed $source
     * @return array
     * @api
     */
    public function getSourceChildPropertiesToBeConverted($source): array
    {
        //$this->log('--> FileReferenceConverter');
        return [];
    }
}
