<?php

namespace PHPNative\Async;

class TaskManager
{
    private static ?TaskManager $instance = null;
    private array $tasks = [];

    private function __construct()
    {
    }

    /**
     * Get singleton instance
     */
    public static function getInstance(): TaskManager
    {
        if (self::$instance === null) {
            self::$instance = new TaskManager();
        }
        return self::$instance;
    }

    /**
     * Add a new task and start it
     */
    public function addTask(AsyncTask $task): void
    {
        $this->tasks[] = $task;
        $task->start();
    }

    /**
     * Create and start a new async task
     */
    public function runAsync(callable $task): AsyncTask
    {
        $asyncTask = new AsyncTask($task);
        $this->addTask($asyncTask);
        return $asyncTask;
    }

    /**
     * Update all running tasks (call this in your main loop)
     */
    public function update(): void
    {
        foreach ($this->tasks as $key => $task) {
            $task->update();

            // Remove completed tasks
            if ($task->isCompleted()) {
                unset($this->tasks[$key]);
            }
        }
    }

    /**
     * Get count of running tasks
     */
    public function getRunningTaskCount(): int
    {
        return count($this->tasks);
    }

    /**
     * Check if any tasks are running
     */
    public function hasRunningTasks(): bool
    {
        return count($this->tasks) > 0;
    }
}
