<?php
namespace SabaiApps\Directories\Component\Voting\Type;

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Voting\Model\Vote;
use SabaiApps\Directories\Link;
use SabaiApps\Directories\Request;

abstract class AbstractType implements IType {

	protected $_application, $_name, $_info;

	public function __construct( Application $application, $name ) {
		$this->_application = $application;
		$this->_name        = $name;
	}

	public function votingTypeIsEnabled() {
		return true;
	}

	public function votingTypeInfo( $key = null ) {
		if ( ! isset( $this->_info ) ) {
			$this->_info  = $this->_application->Filter( 'voting_type_info', (array) $this->_votingTypeInfo(), array( $this->_name ) );
			$this->_info += array(
				'table_sortable_headers'  => array( 'value', 'created' ),
				'table_timestamp_headers' => array( 'created' ),
				'table_default_header'    => 'created',
			);
		}

		return isset( $key ) ? ( isset( $this->_info[ $key ] ) ? $this->_info[ $key ] : null ) : $this->_info;
	}

	public function votingTypeButtonSettingsForm( Bundle $bundle, array $settings, array $parents = array() ) {
		return array();
	}

	public function votingTypeOnVoteButtonLink( Link $link, IEntity $entity, array $settings, $displayName ) {}
	public function votingTypeOnVoteEntityForm( array $form, IEntity $entity, ?Vote $currentVote = null ) {
		return $form;
	}

	public function votingTypeOnVoteEntity( IEntity $entity, array &$response, Request $request ) {}
	abstract protected function _votingTypeInfo();

	public function votingTypeTableRow( Vote $vote, array $tableHeaders ) {
		$ret = array();
		if ( isset( $tableHeaders['created'] ) ) {
			$ret['created'] = $this->_application->System_Date_datetime( $vote->created, true );
		}
		if ( isset( $tableHeaders['author'] ) ) {
			$ret['author'] = $this->_application->UserIdentityHtml( $vote->User, 'link_thumb_s' );
		}
		if ( isset( $tableHeaders['value'] ) ) {
			$ret['value'] = '<i class="' . $this->votingTypeInfo( 'icon' ) . '"></i> ' . $vote->value;
		}
		if ( isset( $tableHeaders['comment'] ) ) {
			$ret['comment'] = $this->_application->H( $vote->comment );
		}
		if ( isset( $tableHeaders['entity'] ) ) {
			$ret['entity'] = '';
			if ( ( $bundle = $this->_application->Entity_Bundle( $vote->bundle_name ) )
				&& ( $entity = $this->_application->Entity_Entity( $bundle->entitytype_name, $vote->entity_id ) )
			) {
				if ( $this->_application->getPlatform()->isAdmin() ) {
					$ret['entity'] = '<a href="' . $this->_application->Entity_AdminUrl( $entity ) . '">' . $this->_application->H( $this->_application->Entity_Title( $entity ) ) . '</a>';
				} else {
					$ret['entity'] = $entity->isPublished() ? $this->_application->Entity_Permalink( $entity ) : $this->_application->H( $this->_application->Entity_Title( $entity ) );
				}
			}
		}
		return $ret;
	}
}
