<?php

namespace App\Controller;

use App\Service\KeyLighterVersioner;
use Kadet\Highlighter\KeyLighter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class LanguagesAction
{
    private $keylighter;
    private $versioner;

    public function __construct(KeyLighter $keylighter, KeyLighterVersioner $versioner)
    {
        $this->keylighter = $keylighter;
        $this->versioner  = $versioner;
    }

    /**
     * @Route("/languages", name="ajax_languages", methods={"GET"})
     */
    public function __invoke()
    {
        return new JsonResponse($this->getLanguages()->values()->all());
    }

    private function getLanguages()
    {
        switch (true) {
            case version_compare(KeyLighter::VERSION, '0.9-dev', '>='):
                $languages = require $this->versioner->getCurrentDir() . '/Config/metadata.php';

                return collect($languages)->flatMap(function ($metadata) {
                    return collect($metadata['name'])->map(function ($name) use ($metadata) {
                        return [
                            'class' => $metadata[0],
                            'name' => $name,
                            'standalone' => $metadata['standalone'],
                            'embeddable' => $metadata['injectable'],
                        ];
                    });
                });

            default:
                $languages = collect($this->keylighter->registeredLanguages('name', true));

                return $languages->map(function ($class, $language) {
                    return [
                        'name'       => $language,
                        'class'      => $class,
                        'standalone' => true,
                        'embeddable' => true,
                    ];
                });
        }
    }
}
