<?php

namespace HelpGent\App\BackgroundProcessors;

defined( 'ABSPATH' ) || exit;

use Exception;
use HelpGent\App\BackgroundProcessors\BackgroundProcess;

class BackgroundProcessor {
    protected BackgroundProcess $background_process;

    protected bool $run_task_async = true;

    public function __construct( string $identifier, bool $run_task_async = true ) {
        $this->background_process = new BackgroundProcess( $identifier, $run_task_async );
        $this->run_task_async     = $run_task_async;
    }

    public function get_background_process(): BackgroundProcess {
        return $this->background_process;
    }

    /**
     * @param array $tasks
     * @throws Exception
     * @return void
     */
    public function run( array $tasks ): void {
        if ( $this->background_process->is_active() ) {
            if ( ! $this->background_process->is_processing() ) {
                $this->background_process->dispatch();
            }
            return;
        }

        if ( $this->run_task_async ) {
            foreach ( $tasks as $task ) {
                $this->background_process->push_to_queue( $task );
            }
        } else {
            $this->background_process->push_to_queue( $tasks );
        }

        $this->background_process->before_init();
        $this->background_process->save()->dispatch();
    }
}