<?php
namespace SabaiApps\Directories\Component\WordPressContent\SystemTool;

use SabaiApps\Directories\Component\System\Tool\AbstractTool;
use SabaiApps\Directories\Context;

class AssignFeaturedImagesSystemTool extends AbstractTool {

	protected function _systemToolInfo() {
		return array(
			'label'       => __( 'Assign featured images', 'directories-pro' ),
			'description' => __( 'This tool assigns or unassigns featured images for posts and terms based on each content type’s image settings.', 'directories-pro' ),
			'weight'      => 60,
		);
	}

	public function systemToolSettingsForm( $step, array $values, array $parents = array(), ?Context $context = null ) {
		$options = $options_disabled = array();
		foreach ( $this->_application->Entity_Bundles_sort() as $bundles ) {
			foreach ( $bundles as $bundle ) {
				if ( ! in_array( $bundle->entitytype_name, array( 'post', 'term' ) )
					|| $bundle->isAlias()
				) {
					continue;
				}

				$bundle_type_info = $this->_application->Entity_BundleTypeInfo( $bundle );
				if ( ! isset( $bundle_type_info['entity_image'] ) ) {
					continue;
				}

				$options[ $bundle->name ] = $bundle->getGroupLabel() . ' - ' . $bundle->getLabel( 'singular' );

				if ( empty( $bundle->info['entity_image'] ) ) {
					$options_disabled[] = $bundle->name;
					continue;
				}
				if ( $bundle->entitytype_name === 'post' ) {
					if ( empty( $bundle->info['wp_post_thumbnail'] ) ) {
						$options_disabled[] = $bundle->name;
						continue;
					}
				} elseif ( $bundle->entitytype_name === 'term' ) {
					if ( empty( $bundle->info['wp_term_thumbnail'] ) ) {
						$options_disabled[] = $bundle->name;
						continue;
					}
				}
			}
		}

		return array(
			'bundles' => array(
				'#type'             => 'checkboxes',
				'#title'            => __( 'Select content types', 'directories-pro' ),
				'#options'          => $options,
				'#options_disabled' => $options_disabled,
				'#default_value'    => null,
				'#required'         => true,
				'#horizontal'       => true,
			),
			'action'  => array(
				'#type'          => 'select',
				'#title'         => __( 'Assign / Unassign', 'directories-pro' ),
				'#options'       => array(
					'assign'   => __( 'Assign featured images where applicable', 'directories-pro' ),
					'unassign' => __( 'Unassign all featured images', 'directories-pro' ),
				),
				'#default_value' => 'assign',
				'#required'      => true,
				'#horizontal'    => true,
			),
			'num'     => array(
				'#type'          => 'slider',
				'#title'         => __( 'Number of items to process per request', 'directories-pro' ),
				'#horizontal'    => true,
				'#default_value' => 50,
				'#min_value'     => 1,
				'#max_value'     => 100,
				'#integer'       => true,
				'#required'      => true,
			),
		);
	}

	public function systemToolInit( array $settings, array &$storage, array &$logs, ?Context $context = null ) {
		$ret = array();
		if ( ! empty( $settings['bundles'] ) ) {
			foreach ( $settings['bundles'] as $bundle_name ) {
				if ( ! $bundle = $this->_application->Entity_Bundle( $bundle_name ) ) {
					continue;
				}

				$ret[ $bundle->name ] = $this->_application->Entity_Query( $bundle->entitytype_name, $bundle->name )->count();
			}
		}

		return $ret;
	}

	public function systemToolRunTask( $task, array $settings, $iteration, $total, array &$storage, array &$logs, ?Context $context = null ) {
		if ( ! $bundle = $this->_application->Entity_Bundle( $task ) ) {
			return false;
		}

		$paginator = $this->_application->Entity_Query( $bundle->entitytype_name, $bundle->name )
			->sortById()
			->paginate( $settings['num'] )
			->setCurrentPage( $iteration );
		$unassign  = $settings['action'] === 'unassign';
		if ( $entities = $paginator->getElements() ) {
			foreach ( $entities as $entity ) {
				if ( $bundle->entitytype_name === 'post' ) {
					$this->_application->WordPressContent_Util_maybeSetPostThumbnail( $bundle, $entity, $unassign, true );
				} elseif ( $bundle->entitytype_name === 'term' ) {
					$this->_application->WordPressContent_Util_maybeSetTermThumbnail( $bundle, $entity, $unassign );
				}
			}
		}

		$offset            = $paginator->getElementOffset();
		$logs['success'][] = sprintf(
			'Assigned featured images for %s (%d - %d)',
			$bundle->getLabel(),
			$offset + 1,
			$offset + $paginator->getElementLimit()
		);

		return $paginator->getElementLimit();
	}
}
