<?php

namespace Velis\Lang;

use Velis\App;
use Velis\Lang\LangVariant\OverloadedLang;
use Velis\Lang\LangVariant\OverloadedLangs;

/**
 * @author Damian Kurek <damian.kurek@velistech.com>
 */
class LangVariant
{
    protected string $variantAcro;

    protected OverloadedLangs $overloadedLangs;

    public function __construct(string $variant)
    {
        $this->variantAcro = mb_strtoupper($variant);
        $this->overloadedLangs = OverloadedLangs::load($this, App::getService('db'));
    }

    /**
     * @param string $acronym
     * @return bool
     */
    public function hasVariantAcronym(string $acronym): bool
    {
        $overloadedLangs = $this->getOverloadedLangs();
        if (!$overloadedLangs) {
            return false;
        }

        return !empty(array_filter($overloadedLangs, function ($lang) use ($acronym) {
            return $lang->getKey() === $acronym;
        }));
    }


    /**
     * @param string $acronym
     * @return string
     */
    public function getAcronymForVariant(string $acronym): string
    {
        if ($this->hasVariantAcronym($acronym)) {
            return $acronym . '_' . $this->variantAcro;
        }

        return $acronym;
    }


    /**
     * @return string
     */
    public function getAcro(): string
    {
        return $this->variantAcro;
    }

    /**
     * @return OverloadedLang[]
     */
    public function getOverloadedLangs(): array
    {
        return $this->overloadedLangs->get();
    }

    /**
     * @return string[]
     */
    public function getOverloadedLangsMap(): array
    {
        $map = [];
        foreach ($this->getOverloadedLangs() as $lang) {
            $map[$lang->getKey()] = $lang->getOverloadedKey();
        }
        return $map;
    }

    /**
     * @return void
     */
    public function clearOverloadedLangs(): void
    {
        $this->overloadedLangs->clearCache();
    }
}
