<?php
namespace SabaiApps\Directories\Component\View\WordPressBlock;

use SabaiApps\Directories\Component\WordPress\Block\AbstractBlock;
use SabaiApps\Directories\Exception\RuntimeException;
use SabaiApps\Directories\Component\Entity\Model\Bundle;

class ViewFilterWordPressBlock extends AbstractBlock {

	protected function _wordpressBlockInfo() {
		return array(
			'title'       => _x( 'Filter Form', 'WordPress block name', 'directories-pro' ),
			'description' => __( 'Displays a filter form.', 'directories-pro' ),
			'package'     => 'directories-pro',
			'icon'        => 'filter',
		);
	}

	public function wordpressBlockEditorVars() {
		$bundles = array(
			array(
				'value' => 'auto',
				'label' => __( 'Auto-detect', 'directories-pro' ),
			),
		);
		foreach ( $this->_application->Entity_Bundles() as $bundle ) {
			if ( $this->_isFilterEnabled( $bundle ) ) {
				$bundles[] = array(
					'value' => $bundle->name,
					'label' => $bundle->getGroupLabel() . ' - ' . $bundle->getLabel(),
				);
			}
		}

		return array(
			'bundles'       => $bundles,
			'cache_options' => $this->_getCacheOptions(),
		);
	}

	public function wordpressBlockRender( array $attributes, $content, $isBlockEditorRequest ) {
		if ( empty( $attributes['bundle'] ) ) {
			throw new RuntimeException( 'No bundle specified.' );
		}
		if ( ! empty( $settings['hideOnMobile'] ) && $this->_application->isMobile() ) {
			return '';
		}
		if ( $attributes['bundle'] === 'auto' ) {
			if ( $isBlockEditorRequest ) {
				return;
			}

			if ( $directory_name = $this->_getCurrentDirectory() ) {
				foreach ( $this->_application->Entity_Bundles( null, $directory_name ) as $_bundle ) {
					if ( $this->_isFilterEnabled( $_bundle ) ) {
						$bundle = $_bundle;
						break;
					}
				}
			}
			if ( empty( $bundle ) ) {
				return '';
			}
			return '<div class="drts-view-entities-filter-form-placeholder" data-bundle-group="' . $bundle->group . '" data-bundle-type="' . $bundle->type . '"></div>';
		}

		if ( ( ! $bundle = $this->_application->Entity_Bundle( $attributes['bundle'] ) )
			|| ! $this->_isFilterEnabled( $bundle )
		) {
			throw new RuntimeException( 'Invalid bundle specified: ' . $attributes['bundle'] );
		}

		// if ($isBlockEditorRequest) return;

		$cache = null;
		if ( isset( $attributes['cacheLifetime'] )
			&& ( $attributes['cacheLifetime'] = intval( $attributes['cacheLifetime'] ) )
		) {
			$cache = $attributes['cacheLifetime'];
		}
		return $this->_render(
			$bundle->getPath() . '/filter',
			array(),
			$cache
		);
	}

	protected function _isFilterEnabled( Bundle $bundle ) {
		return ! empty( $bundle->info['is_primary'] )
			&& $this->_application->getComponent( 'View' )->isFilterable( $bundle );
	}
}
