<?php


namespace AutoAdmin\Bundle\Seo\Extractor;


use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Model\TranslationInterface;
use AutoAdmin\Bundle\Seo\Model\SeoContentTranslationInterface;

abstract class AbstractExtractor implements ExtractorInterface
{
    protected function sanitize(string $input): string
    {
        return strip_tags($input);
    }

    protected function isTranslation(object $subject): bool
    {
        return $subject instanceof TranslationInterface && $subject->getTranslatable() !== null;
    }

    protected function isTranslatable(object $subject): bool
    {
        return $subject instanceof TranslatableInterface && $subject->getCurrentTranslation() !== null;
    }

    protected function isUntranslatedContent(object $subject): bool
    {
        return $subject instanceof SeoContentTranslationInterface;
    }

    /**
     * @param object $subject
     * @return array<TranslatableInterface,TranslationInterface>
     */
    protected function getTranslatableTranslationObjects(object $subject): array
    {
        if ($this->isTranslatable($subject)) {
            $translatable = $subject;
            $translation = $subject->getCurrentTranslation();
        } elseif ($this->isTranslation($subject)) {
            $translation = $subject;
            $translatable = $subject->getTranslatable();
        } elseif ($this->isUntranslatedContent($subject)) {
            // untranslated content, self act as translatable and translation
            $translatable = $translation = $subject;
        } else {
            throw new \Exception('Main content should implement some kind of SEO');
        }

        return [$translatable, $translation];
    }

    /**
     * @return TranslatableInterface|null
     */
    protected function getHomepage(): ?object
    {
        return $this->em->getRepository('App\\Entity\\Page')->contentFindOneBy(['_.homepage' => true,]);
    }
}