<?php
namespace SabaiApps\Directories\Component\Entity\FieldWidget;

use SabaiApps\Directories\Request;
use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class ReferenceFieldWidget extends Field\Widget\AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'            => __( 'Autocomplete text field', 'directories-pro' ),
			'field_types'      => array( $this->_name ),
			'accept_multiple'  => false,
			'repeatable'       => true,
			'default_settings' => array(
				'own_only'    => false,
				'num_suggest' => 5,
			),
		);
	}

	public function fieldWidgetSettingsForm( $fieldType, Bundle $bundle, array $settings, array $parents = array(), array $rootParents = array() ) {
		return array(
			'own_only'    => array(
				'#title'         => __( 'Auto-suggest own content items only', 'directories-pro' ),
				'#type'          => 'checkbox',
				'#default_value' => ! empty( $settings['own_only'] ),
			),
			'num_suggest' => array(
				'#title'         => __( 'Number of auto suggested items to display', 'directories-pro' ),
				'#type'          => 'slider',
				'#default_value' => $settings['num_suggest'],
				'#min_value'     => 1,
				'#max_value'     => 20,
			),
		);
	}

	public function fieldWidgetForm( Field\IField $field, array $settings, $value = null, ?IEntity $entity = null, array $parents = array(), $language = null ) {
		if ( ! $bundle = $this->_getReferenceFieldBundle( $field ) ) {
			return;
		}

		return array(
			'#type'                     => 'autocomplete',
			'#default_value'            => isset( $value ) ? $this->_getValueForForm( $value ) : null,
			'#select2'                  => true,
			'#select2_ajax'             => true,
			'#select2_ajax_url'         => $this->_getAjaxUrl( $bundle, $settings, $entity, $language ),
			'#select2_item_text_key'    => 'title',
			'#default_options_callback' => array( array( $this, '_getDefaultOptions' ), array( $bundle->entitytype_name, $bundle->name ) ),
		);
	}

	protected function _getValueForForm( $value ) {
		return $value instanceof IEntity ? $value->getId() : $value;
	}

	public function _getDefaultOptions( $defaultValue, array &$options, $entityType, $bundleName ) {
		foreach ( $this->_application->Entity_Types_impl( $entityType )->entityTypeEntitiesByIds( $defaultValue, $bundleName ) as $entity ) {
			$options[ $entity->getId() ] = $this->_application->Entity_Title( $entity );
		}
	}

	protected function _getReferenceFieldBundle( Field\IField $field ) {
		return $this->_application->Field_Type( $field->getFieldType() )->getReferenceFieldBundle( $field );
	}

	protected function _getAjaxUrl( Bundle $bundle, array $settings, ?IEntity $entity = null, $language = null ) {
		$params = array(
			'bundle'                    => $bundle->name,
			Request::PARAM_CONTENT_TYPE => 'json',
			'language'                  => $language,
			'num'                       => isset( $settings['num_suggest'] ) ? $settings['num_suggest'] : 5,
		);
		if ( ! empty( $settings['own_only'] ) ) {
			if ( ! $this->_application->getUser()->isAdministrator() ) {
				if ( isset( $entity )
					&& $entity->getAuthorId()
				) {
					$params['user_id'] = $entity->getAuthorId();
				} else {
					// @todo Need extra query for anonymous users
					$params['user_id'] = $this->_application->getUser()->id;
				}
			}
		}

		return $this->_application->MainUrl(
			'/_drts/entity/' . $bundle->type . '/query',
			$params,
			'',
			'&'
		);
	}
}
