<?php
namespace SabaiApps\Directories\Component\Dashboard\DisplayButton;

use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Application;

abstract class AbstractDisplayButton extends Display\Button\AbstractButton {

	protected $_route, $_params;

	public function __construct( Application $application, $name, $route, array $params = array() ) {
		parent::__construct( $application, $name );
		$this->_route  = $route;
		$this->_params = $params;
	}

	protected function _checkAccess( Bundle $bundle, IEntity $entity, array $settings, $displayName, $route ) {
		return $this->_application->Entity_IsRoutable( $bundle, $route, $entity );
	}

	public function displayButtonLink( Bundle $bundle, IEntity $entity, array $settings, $displayName ) {
		if ( ! $this->_checkAccess( $bundle, $entity, $settings, $displayName, $this->_route ) ) {
			return;
		}

		if ( ! $url = $this->_getUrl( $bundle, $entity, $settings, $displayName ) ) {
			return;
		}

		$label   = $this->_getLabel( $bundle, $entity, $settings );
		$options = array();
		if ( ! empty( $settings['_icon'] ) ) {
			$options['icon'] = 'fa-fw ' . $settings['_icon'];
		}
		$attr = array(
			'class' => $settings['_class'],
			'style' => $settings['_style'],
		);
		if ( $modal = $this->_isModal( $bundle, $entity, $settings ) ) {
			settype( $modal, 'array' );
			$this->_loadModalAssets( $bundle, $entity, $settings );
			$options['container'] = 'modal';
			if ( isset( $modal['size'] ) ) {
				$options['modalSize'] = $modal['size'];
			}
			$attr += array(
				'data-modal-title'  => $this->_getModalTitle( $bundle, $entity, $label ),
				'data-modal-danger' => empty( $modal['danger'] ) ? 0 : 1,
			);
		}
		$link = $this->_application->LinkTo( $label, $url, $options, $attr );

		return $this->_application->Filter( 'dashboard_post_display_button_link', $link, array( $entity, $displayName ) );
	}

	abstract protected function _getUrl( Bundle $bundle, IEntity $entity, array $settings, $displayName );

	protected function _getLabel( Bundle $bundle, IEntity $entity, array $settings ) {
		return $settings['_label'];
	}

	protected function _isModal( Bundle $bundle, IEntity $entity, array $settings ) {
		return false;
	}

	protected function _getModalTitle( Bundle $bundle, IEntity $entity, $label ) {
		return $this->_application->Entity_Title( $entity ) . ' - ' . $label;
	}

	protected function _loadModalAssets( Bundle $bundle, IEntity $entity, array $settings ) {
		$this->_application->getPlatform()->addJsFile( 'form.min.js', 'drts-form', array( 'drts' ) ); // for modal form
	}
}
