<?php

namespace HelpGent\App\BackgroundServices;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\BackgroundProcessors\BackgroundProcessor;
use HelpGent\App\BackgroundProcessors\BackgroundProcess;

abstract class BackgroundService {
    public BackgroundProcessor $background_processor;

    public BackgroundProcess $background_process;

    protected array $tasks = [];

    public function __construct() {
        $this->boot();
        $this->background_process = $this->background_processor->get_background_process();
    }

    abstract public function boot();

    public function add_task( callable $callback, array $args = [] ): self {
        $this->tasks[] = [ 'callback' => $callback, 'args' => $args ];

        return $this;
    }

    public function add_service_task( string $callback_name, array $args = [] ): self {
        if ( method_exists( $this, $callback_name ) ) {
            $this->tasks[] = [ 'callback' => [ get_called_class(), $callback_name ], 'args' => $args ];
            return $this;
        }

        return $this;
    }

    public function run(): void {
        if ( empty( $this->tasks ) ) {
            return;
        }

        $this->background_processor->run( $this->tasks );
    }
}