<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Config;

/**
 * Give help to interact with the config for alt names.
 */
class ConfigPersonAltNamesHelper
{
    /**
     * @param mixed[] $config
     */
    public function __construct(
        /**
         * the raw config, directly from the container parameter.
         */
        private $config,
    ) {}

    /**
     * get the choices as key => values.
     *
     * @return array<string, array<string, string>> where the key is the altName's key, and the value is an array of TranslatableString
     */
    public function getChoices(): array
    {
        $choices = [];

        foreach ($this->config as $entry) {
            $labels = $entry['labels'];
            $lang = false;
            $label = false;
            $cur = reset($labels);

            while ($cur) {
                if ('lang' === key($labels)) {
                    $lang = current($labels);
                }

                if ('label' === key($labels)) {
                    $label = current($labels);
                }

                if (false !== $lang && false !== $label) {
                    $choices[$entry['key']][$lang] = $label;
                    $lang = false;
                    $label = false;
                }
                $cur = next($labels);
            }
        }

        return $choices;
    }

    /**
     * Return true if at least one alt name is configured.
     */
    public function hasAltNames(): bool
    {
        return [] !== $this->config;
    }
}
