<?php

namespace App\Service;

use Pimcore\Model\DataObject\ClassDefinition\LinkGeneratorInterface;
use Pimcore\Model\DataObject\Concrete;
use Pimcore\Model\DataObject\Localizedfield;
use Pimcore\Model\Document;
use App\Tool\Utils;

class LinkGenerator implements LinkGeneratorInterface
{
	public function generate(object $object, array $params = []): string
	{
		$url = '';
		$language = array_key_exists('language', $params) ? $params['language'] : null;
		if (!$language) {
			// Get language from document or localized field, or default for object.
			// For document.
			if (isset($params['document']) && $params['document'] instanceof Document) {
				$language = $params['document']->getProperty('language');
			}
			// For object, in localized field.
			elseif (isset($params['object']) && $params['object'] instanceof Localizedfield) {
				$language = $params['object']->getLanguage();
			}
			// For object, out of localized field.
			else {
				$language = Utils::getDefaultLanguage();
			}
		}
		if ($object instanceof Concrete) {
			$className = $object->getClassName();
			$staticRouteKey = ltrim(strtolower(preg_replace('/[A-Z]/', '-$0', $className . '-' . $language)), '-');
			if ($staticRouteKey && method_exists($object, 'getName')) {
				if ($slug = Utils::webalize(trim($object->getName($language)))) {
					$params = [
						'id' => $object->getId(),
						'slug' => $slug,
					];
					$url = Utils::url($staticRouteKey, $params);
				}
			}
		}
		return $url;
	}
}
