<?php
namespace Newland\Toubiz\Sync\Neos\Translation;

use Doctrine\ORM\QueryBuilder;
use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Flow\Property\Exception\InvalidPropertyException;
use Newland\Toubiz\Api\Constants\Language;
use Neos\Flow\I18n;

trait TranslatableRepository
{
    /** @var I18n\Service */
    protected $localizationService;

    /** @var array */
    protected $translationConfiguration;

    /** @var string|null */
    protected $language;

    public function injectLocalizationService(I18n\Service $localizationService)
    {
        $this->localizationService = $localizationService;
    }

    public function injectTranslationConfiguration(ConfigurationManager $configurationManager)
    {
        $this->translationConfiguration = (array) $configurationManager->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            'Newland.Toubiz.Sync.Neos.translation'
        );
    }

    /**
     * Override core method to support languages.
     *
     * @see \Neos\Flow\Persistence\Doctrine\Repository::__call
     */
    public function __call($method, $arguments)
    {
        if (empty($this->language)) {
            parent::__call($method, $arguments);
        }

        if (empty($this->alias)) {
            throw new InvalidPropertyException('Property alias must be set on repository.', 1556545106);
        }

        $queryBuilder = $this->createQueryBuilder($this->alias);
        $queryBuilder = $this->addLanguageWhereClause($queryBuilder, $this->alias, $this->language);

        if (isset($method[10]) && strpos($method, 'findOneBy') === 0) {
            $propertyName = lcfirst(substr($method, 9));

            $result = $queryBuilder
                ->andWhere(
                    $queryBuilder->expr()->like(
                        $this->alias . '.' . $propertyName,
                        $queryBuilder->expr()->literal($arguments[0])
                    )
                )
                ->setMaxResults(1)
                ->getQuery()
                ->execute();

            $record = null;
            if (\count($result)) {
                $record = $result[0];
            }

            return $record;
        }

        if (isset($method[8]) && strpos($method, 'countBy') === 0) {
            $propertyName = lcfirst(substr($method, 7));

            return $queryBuilder
                ->andWhere(
                    $queryBuilder->expr()->like(
                        $this->alias . '.' . $propertyName,
                        $queryBuilder->expr()->literal($arguments[0])
                    )
                )
                ->getQuery()
                ->execute()
                ->count();
        }

        if (isset($method[7]) && strpos($method, 'findBy') === 0) {
            $propertyName = lcfirst(substr($method, 6));

            return $queryBuilder
                ->andWhere(
                    $queryBuilder->expr()->like(
                        $this->alias . '.' . $propertyName,
                        $queryBuilder->expr()->literal($arguments[0])
                    )
                )
                ->getQuery()
                ->execute();
        }

        trigger_error('Call to undefined method ' . get_class($this) . '::' . $method, E_USER_ERROR);
    }

    public function setLanguage(string $language = null)
    {
        if ($language) {
            Language::throwIfInvalid($language);
        }
        $this->language = $language;
    }

    /**
     * Creates a new QueryBuilder instance that is prepopulated for this entity name.
     *
     * @param string $alias
     * @param string $indexBy The index for the from.
     *
     * @return QueryBuilder
     */
    public function createQueryBuilder($alias, $indexBy = null)
    {
        return $this->addLanguageWhereClause(
            parent::createQueryBuilder($alias, $indexBy),
            $alias,
            $this->getLanguage()
        );
    }

    protected function addLanguageWhereClause(QueryBuilder $query, string $alias, string $language = null): QueryBuilder
    {
        if (!$language) {
            return $query;
        }

        $languageField = sprintf('%s.language', $alias);
        $where = [
            $query->expr()->eq($languageField, $query->expr()->literal($language)),
        ];

        $strict = $this->translationConfiguration['strict'] ?? false;
        if (!$strict) {
            $where[] = $query->expr()->isNull($languageField);
        }

        return $query->where($query->expr()->orX(...$where));
    }

    protected function getLanguage()
    {
        return $this->language ?? $this->localizationService->getConfiguration()->getCurrentLocale()->getLanguage();
    }
}
