<?php
namespace SabaiApps\Directories\Platform\WordPress;

use SabaiApps\Directories\Platform\IScheduler;

abstract class AbstractScheduler implements IScheduler {

	protected $_platform;

	public function __construct( Platform $platform ) {
		$this->_platform = $platform;
	}

	public function __toString() {
		return __CLASS__;
	}

	public function initActions( array $actions ) {
		foreach ( $actions as $action_name => $action_info ) {
			$args     = $action_info['args'] ?? array();
			$priority = $action_info['priority'] ?? 10;
			add_action(
				$this->_getHookName( $action_name ),
				function () use ( $action_name, $args ) {
					$this->_platform->getApplication()->Action( $action_name, $args );
				},
				$priority,
				count( $args )
			);
			if ( ! empty( $action_info['immediate_actions'] ) ) {
				foreach ( $action_info['immediate_actions'] as $immediate_action => $immediate_action_info ) {
					add_action(
						$this->_getHookName( $immediate_action ),
						function () use ( $immediate_action ) {
							$this->_platform->getApplication()->Action( $immediate_action, func_get_args() );
						},
						$immediate_action_info['priority'] ?? $priority,
						$immediate_action_info['args_count'] ?? 0
					);
				}
			}
		}
	}

	protected function _getHookName( $action ) {
		return 'drts_scheduled_action_' . $action;
	}
}
