<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers;

/**
 * Renders a field summary, i.e. a table of all modified propertys of an object
 *
 * @api
 * @author     Markus Baumgartner <mb@stylesheep.ch>, Internetgalerie AG
 * @package    IgDatapoolFE
 * @subpackage ViewHelpers
 */
class FieldSummaryViewHelper extends \TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper
{
    use ViewHelperTrait;

    public function initializeArguments()
    {
        $this -> registerArgument('object', \TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject::class, 'The object', true);
        $this -> registerArgument('changedValueColor', 'string', 'The bg-color of the changes values', false, '#FF9696');
        $this -> registerArgument('dontPrefixWithModelName', 'boolean', 'Prefix', false, false);
        $this -> registerArgument('hideEmptyValues', 'boolean', 'hide', false, false);
        $this -> registerArgument('fieldList', 'string', 'Comma-separated list of fields to show', false, '*');
        $this -> registerArgument('exclude', 'string', 'Comma-separated list of excluded fields', false, 'uid,pid');
        $this -> registerArgument('noBorder', 'boolean', 'Remove Border', false, true);
    }

    /**
     * renders a summary (mail friendly)
     *
     * @param  TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject $object
     * @return string
     */
    public function render()
    {
        $object = $this->arguments['object'];
        // resolve the fields
        $fields = array();
        if ($this -> arguments['fieldList'] == '*') {
            $fields = array_keys($object -> _getProperties());
        } else {
            $fields = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this -> arguments['fieldList']);
        }
        $fields = array_diff($fields, \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $this -> arguments['exclude']));

        //render
        $html = array();
        //get the tablename for label resolution
        $tablename = \Internetgalerie\IgDatapoolFe\Utility\NeedfulThings::classToTable(get_class($object));
        if (!$this -> arguments['dontPrefixWithModelName']) {
            $html[] = '<strong>' . \Internetgalerie\IgDatapoolFe\Services\LangService::ll($tablename) . '</strong>';
        }
        $borderWidth = intval($this -> arguments['noBorder']);

        $html[] = '<table border="'.$borderWidth.'" cellspacing="0" style="border-collapse:collapse;width:100%">';

        foreach ($fields as $f) {
            $val = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getPropertyPath($object, $f);

            $changed_txt = '';
            if ($object -> _isDirty($f)) {
                $changed_txt = 'background-color:' . $this -> arguments['changedValueColor'] . ';';
            }
            //convert types
            if ($val instanceof \TYPO3\CMS\Extbase\Persistence\ObjectStorage) {
                $val -> rewind();
                $current = $val -> current();
                if ($current instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
                    $name = $current -> getOriginalResource() -> getName();
                    $val = '<a target="_blank" href="' . \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '/' . $current -> getOriginalResource() -> getOriginalFile() -> getPublicUrl() . '">' . basename($name) . '</a>';
                } else {
                    $val = implode('<br />', $val -> toArray());
                }
            } elseif ($val instanceof \DateTime) {
                $val = $val -> format('d.m.Y');
            } elseif ($val instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
                $name = $value -> getOriginalResource() -> getName();
                $val = '<a href="' . \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . '/' . $val -> getOriginalResource() -> getOriginalFile() -> getPublicUrl() . '">' . basename($name) . '</a>';
            }
            //handle empty  values
            if (!$val && $this -> arguments['hideEmptyValues']) {
                continue;
            }

            if (!$val) {
                $val = '&nbsp;';
            }

            //resolve label
            $fieldname = \Internetgalerie\IgDatapoolFe\Utility\NeedfulThings::propertyToField($f);
            $field_label = \Internetgalerie\IgDatapoolFe\Services\LangService::ll($tablename . '.' . $fieldname);

            //changed_txt, fieldlabel, val
            $html[] = '<tr><td style="padding:3px;' . $changed_txt . 'width:150px;font-size:12px;vertical-align:top">' . $field_label . '</td><td style="padding:3px; ' . $changed_txt . 'vertical-align:top;font-size:12px">' . $val . '</td></tr>';
        }
        $html[] = '</table><br />';

        return implode("\n", $html);
    }
}
