<?php

declare(strict_types=1);

namespace XBotControl\Controllers;


use Psr\Http\Message\ServerRequestInterface;

class StaticFilesController
{

    /**
     * Mapping between file extension and MIME type to send in `Content-Type` response header
     *
     * @var array<string,string>
     */
    private $mimetypes = array(
        'atom' => 'application/atom+xml',
        'bz2' => 'application/x-bzip2',
        'css' => 'text/css',
        'gif' => 'image/gif',
        'gz' => 'application/gzip',
        'htm' => 'text/html',
        'html' => 'text/html',
        'ico' => 'image/x-icon',
        'jpeg' => 'image/jpeg',
        'jpg' => 'image/jpeg',
        'js' => 'text/javascript',
        'json' => 'application/json',
        'pdf' => 'application/pdf',
        'png' => 'image/png',
        'rss' => 'application/rss+xml',
        'svg' => 'image/svg+xml',
        'tar' => 'application/x-tar',
        'xml' => 'application/xml',
        'zip' => 'application/zip',
    );
    public function __invoke(ServerRequestInterface $request)
    {


        $path = $request->getUri()->getPath();
        $cleanedPath = $_ENV['APP_DIR'] . '/public' . str_replace($_ENV['BASEURI'], '', $path);

        $stream = new \React\Stream\ReadableResourceStream(fopen($cleanedPath, 'r'), null, 65536);
        $ext = strtolower(substr($path, strrpos($path, '.') + 1));

        return   new \React\Http\Message\Response(
            \React\Http\Message\Response::STATUS_OK,
            [
                'Content-Type' => $this->mimetypes[$ext] ?? 'text/html',
                'Cache-Control' => 'max-age=15552000',
                'Content-length' => filesize($cleanedPath),
                'Expires' => gmdate('D, d M Y H:i:s T', strtotime('next month')),
                'Date' => gmdate('D, d M Y H:i:s T', filemtime($cleanedPath)),
                'Last-modified' => gmdate('D, d M Y H:i:s T',filectime($cleanedPath))

            ],
            $stream 
        );
    }
}
