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

use SabaiApps\Directories\Assets;
use SabaiApps\Directories\Context;

class ViewEntities extends AbstractQueryEntities {

	protected static $_defaultSettings = array(
		'container_template' => 'view_entities_container',
		'push_state'         => true,
		'hide_empty'         => false,
		'no_json'            => false,
	);

	protected function _doExecute( Context $context ) {
		parent::_doExecute( $context );

		if ( $context->isError() ) {
			return;
		}

		// Notify
		$this->Action( 'view_display_entities', array( $context ) );

		// Init context
		if ( ! $context->hasTemplate() ) {
			$context->addTemplate( 'view_entities' );
		}
		$context->setAttributes(
			array(
				'container_template'   => $this->_settings['container_template'],
				'push_state'           => $this->_settings['push_state'],
				'hide_empty'           => $this->_settings['hide_empty'],
				'nav'                  => $context->view->viewModeNav( $context->bundle, $context->settings ),
				'skip_render_entities' => true,
			)
		);
		if ( isset( $context->settings['display'] ) ) {
			if ( empty( $context->settings['display_cache'] )
				|| ( ! empty( $context->settings['display_cache_guest_only'] ) && ! $this->getUser()->isAnonymous() )
				|| ! $this->Filter( 'view_entities_display_is_cacheable', true, array( $context ) )
			) {
				$context->settings['display_cache'] = false;
			}
		}

		// Set template
		if ( $context->getRequest()->isAjax() ) {
			if ( empty( $this->_settings['no_json'] ) ) {
				$context->setContentType( 'json' );
			}
		} else {
			// Load view specific assets if any
			if ( $assets = $context->view->viewModeAssets( $context->bundle, $context->settings ) ) {
				Assets::load( $this->getPlatform(), $assets );
			}
			$context->addExtraHtmlAttributes(
				array(
					'data-view-bundle-name' => $context->bundle->name,
					'data-view-name'        => $context->view_name,
					'data-view-mode'        => (string) $context->view,
				)
			);
		}
	}
}
