<?php
namespace DevOwl\SearchEnginePostType;

use WP_CLI;
use WP_CLI_Command;

/**
 * Provide a WP CLI command to regenerate the index.
 */
class WPCli extends WP_CLI_Command {
    use UtilsProvider;

    const PREFIX_INDEX = 'search-engine-post-type ';

    const PREFIX_CONFIG = 'search-engine-post-type-config ';

    const PREFIX_RESET_QUOTA = 'search-engine-post-type-reset-quota ';

    /**
     * The post type instance.
     *
     * @var SearchEnginePostType
     */
    private $searchEnginePostType;

    /**
     * C'tor.
     *
     * @param SearchEnginePostType $searchEnginePostType
     * @codeCoverageIgnore
     */
    public function __construct($searchEnginePostType) {
        $this->searchEnginePostType = $searchEnginePostType;

        self::setupConstants();
        $this->register();
    }

    /**
     * Register the new command and set our callback.
     */
    public function register() {
        $searchEnginePostType = $this->getSearchEnginePostType();
        $name = $searchEnginePostType->getArg('name');
        $post_type = $searchEnginePostType->getArg('post_type');

        WP_CLI::add_command(
            self::PREFIX_INDEX . $name,
            [$this, 'index'],
            [
                'shortdesc' => sprintf('Flush the index for the %s post type and recreate it.', $post_type),
            ]
        );

        WP_CLI::add_command(
            self::PREFIX_CONFIG . $name,
            [$this, 'configure'],
            [
                'shortdesc' => sprintf('Configure the index for %s post type.', $post_type),
            ]
        );

        WP_CLI::add_command(
            self::PREFIX_RESET_QUOTA . $name,
            [$this, 'resetQuota'],
            [
                'shortdesc' => sprintf('Reset the search queries quota for %s post type.', $post_type),
            ]
        );
    }

    /**
     * Recreate the index.
     */
    public function index() {
        $indexRecords = new IndexRecords($this->getSearchEnginePostType());
        $indexRecords->start();
    }

    /**
     * Configure the index.
     */
    public function configure() {
        $this->getSearchEnginePostType()->getProvider()->configureIndexes();
    }

    /**
     * Reset search quota.
     */
    public function resetQuota() {
        $this->getSearchEnginePostType()->getQuota()->resetQuota();
    }

    /**
     * Getter.
     *
     * @codeCoverageIgnore
     */
    public function getSearchEnginePostType() {
        return $this->searchEnginePostType;
    }
}
