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

use SabaiApps\Directories\Component\View\DisplayElement\FilterDisplayElement;
use SabaiApps\Directories\Exception;
use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity\Model\Bundle;

class ViewFilterDisplayElement extends FilterDisplayElement {

	protected function _getField( $bundleName ) {
		return $this->_getFieldsetField()[1];
	}

	protected function _getFieldsetField() {
		$name = substr( $this->_name, 21 ); // remove fieldset_view_filter_ part
		if ( ( ! $name_parts = explode( '__', $name ) )
			|| count( $name_parts ) !== 3
			|| ( ! $fieldset_field = $this->_application->Entity_Field( $name_parts[1], $name_parts[2] ) )
		) {
			throw new Exception\RuntimeException( sprintf( 'Invalid field %s for bundle %s', $name_parts[2], $name_parts[1] ) );
		}

		return array(
			$name_parts[0], // parent bundle field name
			$fieldset_field,
		);
	}

	protected function _displayElementInfo( Bundle $bundle ) {
		list($field_name, $fieldset_field) = $this->_getFieldsetField();
		if ( ! $field = $this->_application->Entity_Field( $bundle, $field_name ) ) {
			return;
		}

		return array(
			'type'             => 'field',
			'label'            => $field->getFieldLabel() . ' - ' . $fieldset_field->getFieldLabel(),
			'description'      => sprintf( __( 'Field name: %s', 'directories-pro' ), $fieldset_field->getFieldName() ),
			'default_settings' => array(),
			'icon'             => $this->_application->Field_Type( $fieldset_field->getFieldType() )->fieldTypeInfo( 'icon' ),
			'headingable'      => false,
		);
	}

	protected function _displayElementSupports( Bundle $bundle, Display\Model\Display $display ) {
		if ( $display->type !== 'filters' ) {
			return false;
		}

		try {
			$field = $this->_getField( $bundle->name );
		} catch ( \Exception $e ) {
			$this->_application->LogError( $e );
			return false;
		}

		return true;
	}
}
