<?php

namespace Opentalent\OtTemplating\ViewHelpers\Social;

use FluidTYPO3\Vhs\Traits\TemplateVariableViewHelperTrait;
use FluidTYPO3\Vhs\ViewHelpers\Resource\Record\FalViewHelper;
use Opentalent\OtCore\Exception\ApiRequestException;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Service\ImageService;

/**
 *   This view helper give access to the data needed by the Opengraph and twitter meta tags
 *   @see https://www.opengraph.xyz
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:social.metadata as="meta"
 *                            title="My Title"
 *                            description="A description">
 *          <f:debug>{meta}</f:debug>
 *     </ot:social.metadata>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class MetadataViewHelper extends OtAbstractViewHelper
{
    use TemplateVariableViewHelperTrait;

    /**
     * >> Required to prevent typo3 to escape the html output
     * @var boolean
     */
    protected $escapeOutput = false;

    /**
     * @var ImageService
     */
    protected ImageService $imageService;

    /**
     * @param ImageService $imageService
     */
    public function injectImageService(ImageService $imageService)
    {
        $this->imageService = $imageService;
    }

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'as',
            'string',
            'Name of the returned array',
            true
        );
    }

    /**
     * @param $table
     * @param $field
     * @param $uid
     * @return string|null
     */
    private function getFalImagePath($table, $field, $uid): ?string
    {
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
        $queryBuilder->createNamedParameter($table, \PDO::PARAM_STR, ':tablenames');
        $queryBuilder->createNamedParameter($field, \PDO::PARAM_STR, ':fieldname');
        $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT, ':uid_foreign');
        $ref = $queryBuilder
            ->select('r.uid')
            ->from('sys_file_reference', 'r')
            ->where($queryBuilder->expr()->eq('r.table_local', $queryBuilder->expr()->literal('sys_file')))
            ->andWhere($queryBuilder->expr()->eq('r.tablenames', ':tablenames'))
            ->andWhere($queryBuilder->expr()->eq('r.uid_foreign', ':uid_foreign'))
            ->andWhere($queryBuilder->expr()->eq('r.fieldname', ':fieldname'))
            ->andWhere($queryBuilder->expr()->eq('r.deleted', 0))
            ->andWhere($queryBuilder->expr()->eq('r.hidden', 0))
            ->andWhere($queryBuilder->expr()->lte('r.t3ver_state', 0))
            ->andWhere($queryBuilder->expr()->neq('r.pid', -1))
            ->execute()
            ->fetch();

        if ($ref['uid'] == null) {
            return null;
        }

        $image = $this->imageService->getImage($ref['uid'], null, 1);
        return $this->imageService->getImageUri($image, 1);
    }


    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws ApiRequestException|\Exception
     */
    public function render(): string
    {
        // Get current settings
        $as = $this->arguments['as'];

        $uri = $GLOBALS['TYPO3_REQUEST']->getUri();
        $page = $GLOBALS['TSFE']->page;

        // Forced values registered with https://viewhelpers.fluidtypo3.org/fluidtypo3/vhs/5.0.1/Variable/Register/Set.html
        $registered = $GLOBALS["TSFE"]->register;
        $forcedTitle = ($registered['forceSocialTitle'] ?? null);
        $forcedDescription = ($registered['forceSocialDescription'] ?? null);
        $forcedImageUrl = ($registered['forceSocialImageUrl'] ?? '');

        $data = [
            'pageUrl' => (string)$uri,
            'domain' => $uri->getHost(),
        ];

        // Determine OG title
        if ($forcedTitle != null) {
            $data['ogPageTitle'] = $forcedTitle;
        } elseif ($page['og_title'] != null) {
            $data['ogPageTitle'] = $page['og_title'];
        } else {
            $data['ogPageTitle'] = $page['title'];
        }

        // Determine OG description
        if ($forcedDescription != null) {
            $data['ogPageDescription'] = $forcedDescription;
        } elseif ($page['og_description'] != null) {
            $data['ogPageDescription'] = $page['og_description'];
        }

        // Determine OG image
        if ($forcedImageUrl != null) {
            $data['ogImageUrl'] = $forcedImageUrl;
        } elseif ($page['og_image'] == 1) {
            //  we use the typo3 builtin meta tags generator for now
            // $data['ogImageUrl'] = $this->getFalImagePath('pages', 'og_image', $page['uid']);
        }

        // Determine twitter title
        if ($forcedTitle != null) {
            $data['twitterPageTitle'] = $forcedTitle;
        } elseif ($page['twitter_title'] != null) {
            $data['twitterPageTitle'] = $page['twitter_title'];
        } else {
            $data['twitterPageTitle'] = $page['title'];
        }

        // Determine twitter description
        if ($forcedDescription != null) {
            $data['twitterPageDescription'] = $forcedDescription;
        } elseif ($page['twitter_description'] != null) {
            $data['twitterPageDescription'] = $page['twitter_description'];
        }

        // Determine twitter image
        if ($forcedImageUrl != null) {
            $data['twitterImageUrl'] = $forcedImageUrl;
        } elseif ($page['twitter_image'] == 1) {
            //  we use the typo3 builtin meta tags generator for now
            // $data['twitterImageUrl'] = $this->getFalImagePath('pages', 'twitter_image', $page['uid']);
        }

        $variables = [$as => $data];
        return $this->renderChildrenWithVariables($variables);
    }
}
