<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form\FileReference;

use TYPO3\CMS\Fluid\Form\AbstractFileReferenceViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Renders an AJAX File Field in a FileReference.
 */
class FileViewHelper extends AbstractFileReferenceViewHelper
{
    /**
     * Initialize the arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('defaultLangValue', 'string', 'language Value');
        /*
        $this->registerArgument('allowedFileExt', 'string', 'List of allowed file types');
        $this->registerArgument('acceptMimeTypes', 'string', 'Mime Types, i.e. images/*. only these will be shown in the upload selector. accept="" attrib. see http://www.iana.org/assignments/media-types/media-types.xhtml.');
        $this->registerArgument('maxFileSize', 'string', 'Maximum file size in 10KB, 10MB, etc..');
        $this->registerArgument('uploadLabel', 'string', 'Label/Text for upload button', false, 'Datei auswählen...');
        $this->registerArgument('uploadClass', 'string', 'CSS class upload button', false, '');
        */
    }

    /**
     * Renders the upload field with possible resource pointer
     *
     * @return string
     * @api
     */
    public function render(): string
    {
        $this->formUtility->addJsFooter();
        $this->prepareOptions();

        if ($this->dragAndDrop) {
            $this->cssClasses[]='dp-dropzone';
        }

        $value = $this->getValueAttribute();//getValueAttributeAttribute();
        //$value = $this->getUploadedResource();//


        $this->labels = [];
        $this->labels['type_error'] = \Internetgalerie\IgDatapoolFe\Services\LangService::ll('validator.file.invalidType', 'ig_datapool_fe');
        $this->labels['size_error'] = \Internetgalerie\IgDatapoolFe\Services\LangService::ll('validator.file.tooBig', 'ig_datapool_fe');

        return $this->renderHtml($value);
        /*
        //the current File.
        //might be an arary or objectstorage or a fileReferences or NULL.
        $line ='';
        $hideNew = '';
        //echo('IS='.is_object($value) .' zwar='. get_class($value));
        //echo('xx=' . $this->getValueAttribute( false ) );
        if (($value !== null && !($value instanceof \Iterator)) || (($value instanceof \Iterator) && $value->count()>0)) {
            if ($value instanceof \Iterator) {
                // File lists are not implemented yet!
                //throw new \Exception('Upload doesn\'t support StorageObjects/Arrays at the moment. please use object.myfield.0)');
                foreach ($value as $v) {
                    $line .= $this->renderFile($value);
                }
            } else {
                //here.
                $line = $this->renderFile($value);
            }
            if ($line) {
                $hideNew = 'style="display:none"';
            }
        }

        $uploader = $this->renderUploader($value);



        $inputFields = $this->renderInputFields($value, $this->options);
        //$hiddenFields .= '<input type="hidden" name="' . $this->prefixFieldName('__dpFile[]') . '" value="' . $this->hashService->appendHmac($this->arguments['property']) . '" />';

        $output .= '<div class="dp-file" data-labels="' . htmlentities(json_encode($labels)) . '" data-options="' . htmlentities(json_encode($options)) . '">
        <div class="dp-file-line">' . $line . '</div>
        <div class="dp-file-new" ' . $hideNew . '>' . $uploader . '</div>
        <div class="dp-file-progress" style="display:none;"><div class="dp-file-progressBarWrapper"></div><div class="dp-file-percentage">0%</div></div>
        ' . $inputFields . $hiddenFields . '
        </div>';

        return $output ;
        */
    }



    protected function renderInputFields($currentValue, $options)
    {
        $this->registerFieldNameForFormTokenGeneration($this->getName());
        return $this->formUtility->renderFileInputFields($this->getName(), $currentValue, $options);
    }








    /*
    public function renderFile($value)
    {
        return $this->formUtility->renderFile($value);
    }

    protected function renderUploader($value)
    {
        if ($this->hasArgument('defaultLangValue')) {
            if ($value !== null) {
                $select =1;
            } else {
                $select=0;
            }
            $uid = $this->arguments['defaultLangValue'];
            $hashUid = htmlspecialchars($this->hashService->appendHmac((string)$uid));
            $hashNo = htmlspecialchars($this->hashService->appendHmac('-1'));
            return '<select name="' . $this->getName() . '[langFile]" class="dp-file-upload-lang-select">
    <option value="'.$hashNo.'" class="dp-no">Nicht darstellen</option>
    <option value="'.$hashUid.'" class="dp-yes">Gleiches Bild verwenden</option>
    <option value=""'.($select ? ' selected=""' : '').'>Bild hochladen</option>
    </select>
    <div class="dp-file-upload-lang-upload" style="display: none; ">' . $this->formUtility->renderUploader($this->arguments['uploadLabel'], $this->arguments['uploadClass']).'</div>';
        }


        return $this->formUtility->renderUploader($this->arguments['uploadLabel'], $this->arguments['uploadClass']);
    }

    protected function renderInputFields($currentValue, $options)
    {
        $this->registerFieldNameForFormTokenGeneration($this->getName());
        return $this->formUtility->renderFileInputFields($this->getName(), $currentValue, $options);

        $origFilename = $fileVal = '';
        $fileId = '';
        // Orignal Resource
        //echo('render='.get_class($currentValue) .'<br />');

        if ($currentValue instanceof \TYPO3\CMS\Core\Resource\File) {
            //if ($currentValue->getUid() != NULL)
            $fileVal = htmlspecialchars($this->hashService->appendHmac((string)$currentValue ->getUid()));
            $fileId = (string)$currentValue ->getUid();
            $origFilename = (string)$currentValue ->getUid();
            $fileId .= ', '. $origFilename;
        }

        // hashService   appendHmac
        //$inputs = '' .         get_class($currentValue) . ' , fileId=' .  $fileId . ' uid=' . $currentValue->getUid();

        $inputs .= '<input type="hidden" class="mode" name="' . $this->getName() . '[mode]" value="' . htmlspecialchars($this->hashService->appendHmac('sys_file')) .'" />';
        $inputs .= '<input type="hidden" class="newFile" name="' . $this->getName() . '[newFile]" value="" />';
        $inputs .= '<input type="hidden" class="curFile" name="' . $this->getName() . '[curFile]" value="' . $fileVal . '" />' ;
        if ($value instanceof \TYPO3\CMS\Core\Resource\File) {
            $inputs .= '<input type="hidden" class="uid" name="' . $this->getName() . '[fileUid]" value="' . htmlspecialchars($this->hashService->appendHmac((string) $currentValue->getUid())) . '" />';
            $inputs .= '<input type="hidden" class="remove" name="' . $this->getName() . '[remove]" value="0" />';
        }
        $inputs .= '<input type="hidden" class="origFilename" name="' . $this->getName() . '[origFilename]" value="' . $origFilename . '" />';

        $inputs .= '<input type="hidden" name="' . $this->getName() . '[options]" value="' . htmlspecialchars($this->hashService->appendHmac((string)base64_encode(serialize($options)))) . '" />';

        $this->registerFieldNameForFormTokenGeneration($this->getName());
        return $inputs;
    }
    */
}
