<?php

namespace Cadoles\CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class IconChoiceType extends AbstractType
{
    /**
     * Cache for multiple icon fields or sub-requests.
     *
     * @var array
     */
    private $choices;

    private $fontawesomeIconsFile;

    public function __construct($fontawesomeIconsFile)
    {
        // Liste des icones FontAwesome au format JSON
        // Récupéré depuis le dépôt officiel via la commande "make fetch-fontawesome-icons"
        // Voir service.yml
        $this->fontawesomeIconsFile = $fontawesomeIconsFile;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // Pass this flag is necessary to render the label as raw.
        // See below the twig field template for more details.
        $view->vars['raw_label'] = true;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'attr' => [
                // It's the key of the solution and can be done in many ways.
                // Now, the rendered <select> element will have a new font.
                'style' => "font-family: 'FontAwesome';",
                'class' => 'select2-icon',
            ],
            'choices' => $this->getFontAwesomeIconChoices(),
        ]);
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

    protected function getFontAwesomeIconChoices()
    {
        if (null !== $this->choices) {
            return $this->choices;
        }

        $fileContent = file_get_contents($this->fontawesomeIconsFile);
        if (!$fileContent) {
            throw new \Error('Could not load fontawesome icons file');
        }

        $icons = json_decode($fileContent, true);

        foreach ($icons as $iconName => $iconMetadata) {
            foreach ($iconMetadata['free'] as $iconStyle) {
                if ('brands' === $iconStyle) {
                    // On ne propose pas les icônes de marques déposées.
                    continue;
                }
                $iconClass = '';
                switch ($iconStyle) {
                    case 'solid':
                        $iconClass .= ' fas';
                        break;
                    case 'regular':
                        $iconClass .= ' far';
                        break;
                    case 'brands':

                    default:
                        $iconClass .= ' fa';
                        break;
                }
                $iconClass .= ' fa-' . $iconName;
                $this->choices[$iconMetadata['label'] . ' (' . $iconStyle . ')'] = trim($iconClass);
            }
        }

        return $this->choices;
    }
}