<?php


namespace AutoAdmin\Bundle\Content\Context;


use AutoAdmin\Bundle\Content\Entity\Domain;
use AutoAdmin\Bundle\Content\Entity\Locale;
use AutoAdmin\Bundle\Content\Entity\Site;
use RuntimeException;

class SiteContext
{
    protected ?Site $site = null;
    protected ?Locale $locale = null;

    public function getSite(): ?Site
    {
        return $this->site;
    }

    public function setSite(?Site $site): self
    {
        $this->site = $site;

        return $this;
    }

    public function getLocale(): ?Locale
    {
        return $this->locale;
    }

    public function setLocale(?Locale $locale): self
    {
        $this->locale = $locale;

        return $this;
    }

    /**
     * TODO:  remove this ? or really used ?
     */
    public function getDomain(): mixed
    {
        if (null === $this->site || null === $this->locale) {
            throw new RuntimeException('Could not get domain, site or locale is not identified.');
        }

        $matchedLocale = $this->locale;
        $domains = $this->site->getDomains();
        if (empty($domains->toArray())) {
            return null;
        }

        $domains->filter(
            function (Domain $domain) use ($matchedLocale) {
                foreach ($domain->getLocales() as $locale) {
                    if ($locale->getCode() === $matchedLocale->getCode()) {
                        return $domain;
                    }
                }

                return null;
            }
        );

        $domains = array_filter($domains->toArray());

        return array_shift($domains);
    }

    public function __toString(): string
    {
        $string = '';
        $string .= $this->getSite()->getSlug();
        $string .= '//';
        $string .= $this->getLocale()->getCode();

        return $string;
    }
}