<?php

namespace CirrusSearch\Job;

use CirrusSearch\OtherIndexesUpdater;
use CirrusSearch\SearchConfig;
use MediaWiki\MediaWikiServices;
use MediaWiki\Title\Title;
use MediaWiki\WikiMap\WikiMap;

/**
 * Job wrapper around OtherIndexes. Used during page updates.
 *
 * @license GPL-2.0-or-later
 */
class OtherIndex extends CirrusGenericJob {
	/**
	 * Check if we need to make a job and inject one if so.
	 *
	 * @param SearchConfig $config
	 * @param Title[] $titles The title we might update
	 * @param string|null $cluster The name of the cluster to write
	 *  to, or null for all clusters.
	 */
	public static function queueIfRequired( SearchConfig $config, array $titles, $cluster ) {
		$titlesToUpdate = [];
		foreach ( $titles as $title ) {
			if ( OtherIndexesUpdater::getExternalIndexes( $config, $title, $cluster ) ) {
				$titlesToUpdate[] = [ $title->getNamespace(), $title->getText() ];
			}
		}
		if ( $titlesToUpdate ) {
			// Note that we're updating a bunch of titles but we have to pick one to
			// attach to the job so we pick the first one.
			MediaWikiServices::getInstance()->getJobQueueGroup()->push(
				new self( [
					'titles' => $titlesToUpdate,
					'cluster' => $cluster,
				] )
			);
		}
	}

	/**
	 * @return bool
	 */
	protected function doJob() {
		$titles = [];
		foreach ( $this->params['titles'] as [ $namespace, $title ] ) {
			$titles[] = Title::makeTitle( $namespace, $title );
		}
		$otherIdx = OtherIndexesUpdater::buildOtherIndexesUpdater(
			$this->searchConfig,
			$this->params['cluster'],
			WikiMap::getCurrentWikiId()
		);
		$otherIdx->updateOtherIndex( $titles );

		return true;
	}
}
