<?php
namespace SabaiApps\Directories\Component\Fieldset\FieldFilter;

use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field;

class FieldsetFieldFilter extends Field\Filter\AbstractFilter {

	protected function _fieldFilterInfo() {
		return array(
			'label'            => __( 'Location', 'directories-pro' ),
			'field_types'      => array( $this->_name ),
			'default_settings' => array(),
		);
	}

	public function fieldFilterSettingsForm( Field\IField $field, array $settings, array $parents = array() ) {
		if ( ! $fieldset_bundle = $this->_getFieldsetBundle( $field ) ) {
			return;
		}

		$filterable_fields = array();
		$field_types       = $this->_application->Field_Types();
		foreach ( $this->_application->Entity_Field( $fieldset_bundle ) as $field_name => $field ) {
			if ( ! $field_type = @$field_types[ $field->getFieldType() ] ) {
				continue;
			}
			if ( isset( $field_type['entity_types'] )
				&& ! in_array( $bundle->entitytype_name, $field_type['entity_types'] )
			) {
				// the field type does not support the entity type of the current bundle
				continue;
			}

			if ( ! empty( $field_type['filters'] )
				&& $this->_hasSupportedFilter( $field_type['filters'], $field )
			) {
				$ret[] = 'view_filter_' . $field->getFieldName();
			}
		}
		if ( empty( $filterable_fields ) ) {
			return;
		}
	}

	public function fieldFilterDoFilter( Field\Query $query, Field\IField $field, array $settings, $value, array &$sorts ) {
		$fieldset_bundle = $this->_getFieldsetBundle( $field );
	}

	public function fieldFilterIsFilterable( Field\IField $field, array $settings, &$value, ?array $requests = null ) {
		return $this->_getFieldsetBundle( $field ) ? true : false;
	}

	protected function _getFieldsetBundle( Field\IField $field ) {
		$settings = $field->getFieldSettings();
		if ( empty( $settings['bundle'] )
			|| ( ! $bundle = $this->_application->Entity_Bundle( $settings['bundle'] ) )
		) {
			return;
		}

		return $bundle;
	}
}
