<?php
namespace Newland\NeosCommon\Eel\Helper;

/*
 * This file is part of the "neos-common" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */


use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Mvc\ActionRequest;
use Neos\Neos\Domain\Service\ContentContext;

class PageTitleHelper extends ObjectPropertyHelper
{
    /**
     * Override the title of the current page
     *
     * @param Node $node
     * @param ActionRequest $request
     * @param string|null $defaultValue
     * @param bool $appendWebsiteTitle
     * @return string
     *
     * @deprecated with 1.14 - will be removed in 1.15. Use \Newland\MetaTags\Service\MetaDataService
     */
    public function getTitle(
        Node $node,
        ActionRequest $request,
        ?string $defaultValue = '',
        $appendWebsiteTitle = true
    ): string {
        $this->node = $node;
        $this->request = $request;
        $this->value = (string) $defaultValue;

        $this->getConfiguration();

        if ($this->override) {
            $this->setValueFromRequestedRecord();
        }

        $title = $this->metaData->getTitle() ?: (string) $defaultValue;

        if ($appendWebsiteTitle) {
            $title .= ' | ' . $this->getWebsiteTitle();
        }

        return $title;
    }

    /**
     * Get the title of the current site
     *
     * @return string
     */
    private function getWebsiteTitle(): string
    {
        $context = $this->node->getContext();
        if ($context instanceof ContentContext) {
            return $context->getCurrentSite()->getName();
        }
        return '';
    }
}
