<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/** Persist and complete an operator-requested analysis after prerequisite synchronization. */
class Content_Miner_Analysis_Handoff {
	const OPTION = 'content_miner_analysis_handoff';

	/** @var Content_Miner_Analysis_Job */
	private $analysis;

	public function __construct( $analysis ) {
		$this->analysis = $analysis;
		add_action( 'content_miner_ingestion_completed', array( $this, 'handle_ingestion_completed' ) );
	}

	/** Remember the original analysis request until synchronization completes. */
	public function queue( array $locations = array() ) {
		update_option(
			self::OPTION,
			array(
				'status'       => 'waiting_for_sync',
				'locations'    => array_values( array_map( 'strval', $locations ) ),
				'requested_at' => gmdate( 'c' ),
			),
			false
		);
	}

	/** Whether an operator-requested analysis is waiting for synchronization. */
	public function is_pending() {
		$state = get_option( self::OPTION, array() );
		return is_array( $state ) && 'waiting_for_sync' === ( isset( $state['status'] ) ? $state['status'] : '' );
	}

	/** Cancel a stale handoff when analysis can start immediately. */
	public function clear() {
		delete_option( self::OPTION );
	}

	/** Start analysis in the same request that completes prerequisite synchronization. */
	public function handle_ingestion_completed( $ingestion_state ) {
		if ( ! is_array( $ingestion_state ) || 'complete' !== ( isset( $ingestion_state['status'] ) ? $ingestion_state['status'] : '' ) ) {
			return false;
		}
		$state = get_option( self::OPTION, array() );
		if ( ! is_array( $state ) || 'waiting_for_sync' !== ( isset( $state['status'] ) ? $state['status'] : '' ) ) {
			return false;
		}
		$locations = isset( $state['locations'] ) && is_array( $state['locations'] ) ? $state['locations'] : array();
		delete_option( self::OPTION );
		return $this->analysis->start( $locations );
	}
}
