<?php
if (!defined('ABSPATH')) {
    exit;
}

/********************************************************************
 * Copyright (C) 2025 Hassine RIANI (https://upvimeo.com)
 *
 * This file is part of Upvimeo
 *
 * Upvimeo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * Upvimeo is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Upvimeo. If not, see <https://www.gnu.org/licenses/>.
 **********************************************************************/

/**
 * Class UpVimeo_Process_Manager
 *
 * Responsible for setting up the background processes.
 *
 * @license GPLv2
 * @copyright Hassine RIANI (https://upvimeo.com)
 * @since 1.3.0
 */
class UpVimeo_Process_Manager
{
    private $processes = array();

    private $instances = array();

    /**
     * The class singleton isntance
     * @var UpVimeo_Process_Manager
     */
    private static $instance = null;

    /**
     * UpVimeo_Process_Manager constructor.
     */
    private function __construct()
    {
        add_action('plugins_loaded', array($this, 'init'));
    }

    /**
     * Init
     */
    public function init()
    {
        foreach ($this->processes as $key => $process) {
            if (class_exists($process)) {
                $this->instances[$key] = new $process();
            }
        }
    }

    /**
     * Returns the process
     * @param $key
     *
     * @return null|WP_Background_Process|WP_Async_Request
     */
    public function get($key)
    {
        if (isset($this->instances[$key])) {
            return $this->instances[$key];
        }

        if (isset($this->processes[$key]) && class_exists($this->processes[$key])) {
            $this->instances[$key] = new $this->processes[$key]();
            return $this->instances[$key];
        }

        return null;
    }

    /**
     * Push process
     *
     * @param $key
     * @param $className
     */
    public function push($key, $className)
    {
        $this->processes[$key] = $className;
    }

    /**
     * Return all processes
     *
     * @return WP_Background_Process[]|WP_Async_Request[]
     */
    public function all()
    {
        return $this->instances;
    }

    /**
     * @return UpVimeo_Process_Manager
     */
    public static function instance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}
UpVimeo_Process_Manager::instance();
