<?php

namespace App\Controllers;

use App\Blogs\Blogs;
use App\Cache;
use App\Fetching\Gitea;
use App\Fetching\NanoGal;
use App\Utils\Debug;
use App\Fetching\Shaarli;

class Home {
    private $title = 'Home';

    /**
     * Renders the home page content
     *
     * @param array $params An array of parameters for the page rendering
     * @return string The rendered content for the home page
     */
    function index(array $params): string {
        ob_start();

        $lastShaare = Cache::getCache('shaarli.html', 'feed');
        if ($lastShaare === null) {
            $shaarli = new Shaarli($params);
            Cache::unValidateCache('shaarli.html', 'feed');
            Cache::unValidateCache('home.html', 'page');
            $shaarli->getLastBookmark();
            $shaarliCache = $shaarli->makeList();
            if ($params['config']['useCache'] === true) {
                Cache::setCache('shaarli.html', $shaarliCache, 'feed');
            }
            $lastShaare = $shaarliCache;
        }

        $lastAppsUpdates = Cache::getCache('gitea.html', 'feed');
        if ($lastAppsUpdates === null) {
            $gitea = new Gitea($params);
            $gitea->getLastRepo();
            $repoCache = $gitea->makeList();
            Cache::unValidateCache('gitea.html', 'feed');
            Cache::unValidateCache('home.html', 'page');
            if ($params['config']['useCache'] === true) {
                Cache::setCache('gitea.html', $repoCache, 'feed');
            }
            $lastAppsUpdates = $repoCache;
        }

        $lastPost  = Cache::getCache('posts.html', 'feed');
        if ($lastPost === null) {
            $post = new Blogs($params);
            $post->getLastPost();
            $postCache = $post->makeList();
            Cache::unValidateCache('posts.html', 'feed');
            Cache::unValidateCache('home.html', 'page');
            if ($params['config']['useCache'] === true) {
                Cache::setCache('posts.html', $postCache, 'feed');
            }
            $lastPost = $postCache;
        }

        $lastPics = Cache::getCache('nanogal.html', 'feed');
        if ($lastPics === null) {
            $nanogal = new NanoGal($params);
            Cache::unValidateCache('nanogal.html', 'feed');
            Cache::unValidateCache('home.html', 'page');
            $nanogal->getLastBookmark();
            $nanogalCache = $nanogal->makeList();
            if ($params['config']['useCache'] === true) {
                Cache::setCache('nanogal.html', $nanogalCache, 'feed');
            }
            $lastPics = $nanogalCache;
        }

        require __DIR__ . '/../../template/home.php';
        $content = ob_get_contents();
        ob_end_clean();
        return $content;
    }

    function title() {
        return $this->title;
    }
}