<?php
namespace Meramo\mrm_be\Hooks\PageLayoutView;

use \TYPO3\CMS\Core\Utility\GeneralUtility;
use \TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface;
use \TYPO3\CMS\Backend\View\PageLayoutView;
use \TYPO3\CMS\Core\Service\FlexFormService;
use \TYPO3\CMS\Extbase\Utility\LocalizationUtility;

/**
 * Contains a preview rendering for the page module for CTYPE="mrm_be_cm_podcast"
 */
class MrmBeCmPodcastPreviewRenderer implements PageLayoutViewDrawItemHookInterface
{
     /**
    * Preprocesses the preview rendering of a content element of type "My new content element"
    *
    * @param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object
    * @param bool $drawItem Whether to draw the item using the default functionality
    * @param string $headerContent Header content
    * @param string $itemContent Item content
    * @param array $row Record row of tt_content
    * @return void
    */
    public function preProcess(
        PageLayoutView &$parentObject,
        &$drawItem,
        &$headerContent,
        &$itemContent,
        array &$row
    )
    {
        if($row['CType'] === 'mrm_be_cm_podcast') {
            // Hier wird das aussehen der oben angezeigt Komponent festgelegt
            $headerContent = '<b>' . LocalizationUtility::translate('LLL:EXT:mrm_be/Resources/Private/Language/locallang_ttc.xlf:'.$row['CType'].'.title', '').'</b>';
            $ffs = GeneralUtility::makeInstance(FlexFormService::class);
            $flex = $ffs->convertFlexFormContentToArray($row['pi_flexform']);
            $media = [];
            if($flex['media'] == '1') {
                $fileRepository = GeneralUtility::makeInstance('TYPO3\CMS\Core\Resource\FileRepository');
                $fileObjects = $fileRepository->findByRelation('tt_content', 'media', $row['uid']);

                if($fileObjects && sizeOf($fileObjects) >= 1){
                    $media = array(
                      'reference' => $fileObjects[0]->getReferenceProperties(),
                      'original' => $fileObjects[0]->getOriginalFile()->getProperties(),
                      'resource' => $fileObjects[0]
                    );
                  }
            }
            //console_log($media);
            $media = $media['original']['name'];
            
            $transcript = $flex['transcript'];

            $itemContent .= '<div><div style="display: flex;"><img src="/typo3conf/ext/mrm_be/Resources/Public/Icons/'.$row['CType'].'.svg" style="width: 32px; height: 32px; margin-right: 6px;"><div style="min-width: 0;"><strong>'.LocalizationUtility::translate('LLL:EXT:mrm_be/Resources/Private/Language/locallang_ttc.xlf:'.$row['CType'].'.title', '').':</strong><br/>'.$media.'</div></div><div>'.$transcript.'</div></div>';

            $drawItem = false;
        }
    }
}
