<?php

namespace WPDRMS\ASP\Index;

use WPDRMS\ASP\Options\Data\IndexTableOptions;
use WPDRMS\ASP\Patterns\SingletonTrait;

class IndexService {
	use SingletonTrait;

	private function makeManager( array $args = array() ): Manager {
		$asp_it_options = wd_asp()->o['asp_it_options'];
		$default_args   = array();
		foreach ( $asp_it_options as $k => $o ) {
			$default_args[ str_replace('it_', '', $k) ] = $o;
		}
		/**
		 * @var IndexTableOptions $new_options
		 */
		$new_options                                    = $asp_it_options['options'];
		$default_args['attachment_exclude_directories'] = $new_options->attachment_exclude_directories->directories;
		$default_args['attachment_include_directories'] = $new_options->attachment_include_directories->directories;

		return new Manager( array_merge( $default_args, $args ) );
	}

	public function index( array $args = array() ): array {
		return $this->makeManager( $args )->extendIndex( );
	}

	public function indexPost( int $post_id ): bool {
		return $this->makeManager()->indexDocument( $post_id );
	}

	public function delete( ?int $post_id = null ): void {
		if ( $post_id ) {
			$this->makeManager()->removeDocument( $post_id );
		} else {
			$this->makeManager()->emptyIndex();
			$this->makeManager()->beforeIndex();
		}
	}

	public function postsIndexed(): int {
		return $this->makeManager()->getPostsIndexed();
	}

	public function postsToIndexCount(): int {
		return $this->makeManager()->getPostIdsToIndexCount();
	}

	public function totalKeywords(): int {
		return $this->makeManager()->getTotalKeywords();
	}
}
