<?php

namespace App\Controller;

use Kadet\Highlighter\KeyLighter;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class HighlightAction
{
    private $keylighter;
    private $formatter;

    public function __construct(KeyLighter $keylighter)
    {
        $this->keylighter = $keylighter;
        $this->formatter  = $keylighter->getFormatter('html');
    }

    /**
     * @Route("/highlight", name="demo_highlight", methods={"POST"})
     */
    public function __invoke(Request $request)
    {
        $body = json_decode($request->getContent(), true);

        $language = $this->keylighter->languageByName($body['language']);
        $source   = $body['source'];

        $times    = [];

        $tokens = $this->time(function () use ($source, $language) {
            return $language->tokenize($source);
        }, $times['tokenization']);

        $tokens = $this->time(function () use ($tokens, $language) {
            return $language->parse($tokens);
        }, $times['processing']);

        $formatted = $this->time(function () use ($tokens) {
            return $this->formatter->format($tokens);
        }, $times['formatting']);

        $times['total'] = array_sum($times);

        return new JsonResponse([
            'html'  => $formatted,
            'times' => array_map(function ($time) {
                return $time * 1000;
            }, $times),
        ]);
    }

    private function time(callable $call, &$time) {
        $start  = microtime(true);
        $return = $call();
        $time   = microtime(true) - $start;

        return $return;
    }
}
