<?php


namespace App\Controller;

use App\Entity\Document;
use App\Service\DocumentResolver;
use Kadet\Highlighter\KeyLighter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class DocumentationController
 *
 * @package App\Controller
 * @Route("/docs")
 */
class DocumentationController extends AbstractController
{
    private const DEFAULT_FILE = null;
    private $resolver;

    /**
     * HomeController constructor.
     *
     * @param DocumentResolver $resolver
     */
    public function __construct(DocumentResolver $resolver)
    {
        $this->resolver = $resolver;
    }

    public function sidebarAction($path = null)
    {
        $category = function (Document $document) {
            return $document->getMetadata()['category'];
        };

        $title = function (Document $document) {
            return $document->getMetadata()['title'];
        };

        /** @var \App\Entity\Document[][] $result */
        $result = collect($this->resolver->fetch('/Docs/'))
            ->sortBy($title)->sortBy($category)
            ->groupBy($category);

        return $this->render('docs/sidebar.html.twig', [
            'categories' => $result,
            'path'       => $path
        ]);
    }

    /**
     * @Route("/{path}", name="documentation_show", requirements={"path": ".+"})
     */
    public function showAction($path = self::DEFAULT_FILE)
    {
        try {
            if ($path == self::DEFAULT_FILE) {
                $path = $this->getDefaultFile();
            }

            $document = $this->resolver->getDocument('/Docs/'.$path);

            $meta = $document->getMetadata();

            $prev = false;
            $next = false;

            if (isset($meta['next'])) {
                $next = $this->resolver->getDocument('/Docs/'.$meta['next']);
            }

            if (isset($meta['previous'])) {
                $prev = $this->resolver->getDocument('/Docs/'.$meta['previous']);
            }

            return $this->render("docs/document.html.twig", compact('document', 'path', 'prev', 'next'));
        } catch (FileNotFoundException $exception) {
            if ($path == $this->getDefaultFile()) {
                throw new NotFoundHttpException("Documentation starting point for that version is invalid.");
            }

            return $this->redirectToRoute('documentation_show');
        }
    }

    private function getDefaultFile()
    {
        $version = KeyLighter::VERSION;
        $version = str_replace('-', '.0-', $version); // keylighter uses major.minor-

        if (version_compare($version, '0.9.0-dev', '>=')) {
            return '1-installation';
        } elseif (version_compare($version, '0.8.0', '>=')) {
            return 'usage';
        }

        throw new NotFoundHttpException("No documentation was found for that version :(");
    }
}
