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

use SabaiApps\Directories\Component\WordPress\Block\AbstractBlock;
use SabaiApps\Directories\Exception\RuntimeException;

class ViewWordPressBlock extends AbstractBlock {

	protected function _wordpressBlockInfo() {
		return array(
			'title'       => _x( 'View', 'WordPress block name', 'directories-pro' ),
			'description' => __( 'Renders a view for content items in your directory.', 'directories-pro' ),
			'package'     => 'directories-pro',
			'icon'        => 'welcome-widgets-menus',
		);
	}

	public function wordpressBlockEditorVars() {
		$views = $groups = $view_options = $default_views = array();
		foreach ( $this->_application->getModel( 'View', 'View' )->fetch() as $view ) {
			if ( ! $bundle = $this->_application->Entity_Bundle( $view->bundle_name ) ) {
				continue;
			}

			$groups[ $bundle->group ] = $bundle->getGroupLabel();
			$k                        = ! empty( $bundle->info['is_primary'] ) ? 0 : ( empty( $bundle->info['is_taxonomy'] ) ? 1 : 2 );
			$views[ $bundle->group ][ $k ][ $view->id ] = $bundle->getLabel() . ' - ' . $view->getLabel();
			if ( $view->isDefault() ) {
				$default_views[] = $view->id;
			}
		}
		asort( $groups ); // sort by group label
		foreach ( array_keys( $groups ) as $group ) {
			ksort( $views[ $group ] ); // sort by content type
			foreach ( array_keys( $views[ $group ] ) as $k ) {
				asort( $views[ $group ][ $k ] ); // sort by view label
				foreach ( array_keys( $views[ $group ][ $k ] ) as $view_id ) {
					$view_options[] = array(
						'value' => $view_id,
						'label' => $groups[ $group ] . ' - ' . $views[ $group ][ $k ][ $view_id ],
					);
				}
			}
		}

		return array(
			'views'         => $view_options,
			'default_views' => $default_views,
			'cache_options' => $this->_getCacheOptions(),
		);
	}

	protected function _getView( array $attributes ) {
		if ( empty( $attributes['view'] ) ) {
			throw new RuntimeException( 'No view specified.' );
		}
		if ( ( ! $view_id = intval( $attributes['view'] ) )
			|| ( ! $view = $this->_application->getModel( 'View', 'View' )->fetchById( $view_id ) )
		) {
			throw new RuntimeException( 'Invalid view specified: ' . $attributes['view'] );
		}

		return $view;
	}

	public function wordpressBlockRender( array $attributes, $content, $isBlockEditorRequest ) {
		$view = $this->_getView( $attributes );
		if ( $isBlockEditorRequest
			&& ! in_array( $view->mode, array( 'list', 'map' ) )
		) {
			return;
		}

		$settings = array();
		if ( ! $view->isDefault() ) {
			if ( isset( $attributes['queryLimit'] )
				&& is_numeric( $attributes['queryLimit'] )
			) {
				$settings['query']['limit'] = intval( $attributes['queryLimit'] );
			}
			if ( isset( $attributes['queryFields'] )
				&& strlen( $attributes['queryFields'] = trim( $attributes['queryFields'] ) )
			) {
				parse_str( str_replace( '&amp;', '&', $attributes['queryFields'] ), $fields );
				if ( ! empty( $fields ) ) {
					foreach ( $fields as $field_name => $query_str ) {
						if ( is_array( $query_str ) ) {
							$query_str = array_pop( $query_str );
						}
						$settings['query']['fields'][ $field_name ] = $query_str;
					}
				}
			}
		}
		$cache = null;
		if ( isset( $attributes['cacheLifetime'] )
			&& ( $attributes['cacheLifetime'] = intval( $attributes['cacheLifetime'] ) )
		) {
			$cache = $attributes['cacheLifetime'];
		}

		// Remove HTML of the heading block if no title
		if ( trim( wp_strip_all_tags( $content ) ) === '' ) {
			$content = '';
		}

		return $content . $this->_render(
			$this->_application->Entity_Bundle( $view->bundle_name, '', true )->getPath(),
			array(
				'load_view' => $view->name,
				'settings'  => $settings,
			),
			$cache
		);
	}
}
