<?php
namespace Misuzu\Http\Handlers;

use Misuzu\Template;
use Misuzu\Parsers\Parser;

final class InfoHandler extends Handler {
    public function index($response): void {
        $response->setContent(Template::renderRaw('info.index'));
    }

    public function page($response, $request, string ...$parts) {
        $name = implode('/', $parts);
        $document = [
            'content' => '',
            'title' => '',
        ];

        $isIndexDoc = $name === 'index' || str_starts_with($name, 'index/');
        $isMisuzuDoc = $name === 'misuzu' || str_starts_with($name, 'misuzu/');

        if($isMisuzuDoc) {
            $fileName = substr($name, 7);
            $fileName = empty($fileName) ? 'README' : strtoupper($fileName);
            if($fileName !== 'README')
                $titleSuffix = ' - Misuzu Project';
        } elseif($isIndexDoc) {
            $fileName = substr($name, 6);
            $fileName = empty($fileName) ? 'README' : strtoupper($fileName);
            if($fileName !== 'README')
                $titleSuffix = ' - Index Project';
        } else $fileName = strtolower($name);

        if(!preg_match('#^([A-Za-z0-9_]+)$#', $fileName))
            return 404;

        if($fileName !== 'LICENSE' && $fileName !== 'LICENCE')
            $fileName .= '.md';

        $pfx = '';

        if($isIndexDoc)
            $pfx = '/vendor/flashwave/index';
        elseif(!$isMisuzuDoc)
            $pfx = '/docs';

        $fileName = MSZ_ROOT . $pfx . '/' . $fileName;
        $document['content'] = is_file($fileName) ? file_get_contents($fileName) : '';

        if(empty($document['content']))
            return 404;

        if($document['title'] === '') {
            if(str_starts_with($document['content'], '# ')) {
                $titleOffset = strpos($document['content'], "\n");
                $document['title'] = trim(substr($document['content'], 2, $titleOffset - 1));
                $document['content'] = substr($document['content'], $titleOffset);
            } else
                $document['title'] = ucfirst(basename($fileName));

            if(!empty($titleSuffix))
                $document['title'] .= $titleSuffix;
        }

        $document['content'] = Parser::instance(Parser::MARKDOWN)->parseText($document['content']);

        $response->setContent(Template::renderRaw('info.view', [
            'document' => $document,
        ]));
    }
}
