<?php
namespace Misuzu\Forum;

use stdClass;
use Index\Data\IDbConnection;
use Misuzu\Users\UserInfo;

class ForumContext {
    private ForumCategories $categories;
    private ForumTopics $topics;
    private ForumTopicRedirects $topicRedirects;
    private ForumPosts $posts;

    private array $totalUserTopics = [];
    private array $totalUserPosts = [];

    public function __construct(IDbConnection $dbConn) {
        $this->categories = new ForumCategories($dbConn);
        $this->topics = new ForumTopics($dbConn);
        $this->topicRedirects = new ForumTopicRedirects($dbConn);
        $this->posts = new ForumPosts($dbConn);
    }

    public function getCategories(): ForumCategories {
        return $this->categories;
    }

    public function getTopics(): ForumTopics {
        return $this->topics;
    }

    public function getTopicRedirects(): ForumTopicRedirects {
        return $this->topicRedirects;
    }

    public function getPosts(): ForumPosts {
        return $this->posts;
    }

    // should be replaced by a static counter
    public function countTotalUserTopics(UserInfo|string|null $userInfo): int {
        if($userInfo === null)
            return 0;

        $userId = $userInfo instanceof UserInfo ? $userInfo->getId() : $userInfo;
        if(array_key_exists($userId, $this->totalUserTopics))
            return $this->totalUserTopics[$userId];

        return $this->totalUserTopics[$userId] = $this->topics->countTopics(userInfo: $userInfo, deleted: false);
    }

    // should be replaced by a static counter
    public function countTotalUserPosts(UserInfo|string|null $userInfo): int {
        if($userInfo === null)
            return 0;

        $userId = $userInfo instanceof UserInfo ? $userInfo->getId() : $userInfo;
        if(array_key_exists($userId, $this->totalUserPosts))
            return $this->totalUserPosts[$userId];

        return $this->totalUserPosts[$userId] = $this->posts->countPosts(userInfo: $userInfo, deleted: false);
    }
}
