<?php

namespace App\Service;

use App\Tool\Utils;
use Pimcore\Cache;
use Pimcore\Logger;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\ClassDefinition\CalculatorClassInterface;
use Pimcore\Model\DataObject\Data\CalculatedValue;

class ValueCalculator implements CalculatorClassInterface
{
	/**
	 * @param DataObject\Concrete $object
	 * @param CalculatedValue     $context
	 *
	 * @return string
	 */
	public function compute(DataObject\Concrete $object, CalculatedValue $context): string
	{
		switch ($context->getFieldname()) {
			case 'url':
				return self::getUrl($object, $context->getPosition());
			default:
				Logger::error('CALCULATING VALUE - unsupported field name: '.$context->getFieldname());
				break;
		}
		return '';
	}

	/**
	 * @param DataObject\Concrete $object
	 * @param CalculatedValue     $context
	 *
	 * @return string
	 */
	public function getCalculatedValueForEditMode(DataObject\Concrete $object, CalculatedValue $context): string
	{
		return self::compute($object, $context, true);
	}

	/**
	 * @param DataObject\Concrete $object
	 * @param string $language
	 *
	 * @return string
	 */
	public static function getUrl(DataObject\Concrete $object, string $language = null, array $params = []): string
	{
		if (!$language) {
			$language = Utils::getDefaultLanguage();
		}
		$url = '';
		if ($realObject = ($object instanceof DataObject\Concrete)) {
			if ($linkGenerator = $object->getClass()->getLinkGenerator()) {
				$url = $linkGenerator->generate($object, ['language' => $language]);
			}
		}
		return $url;
	}
}
