<?php
namespace SabaiApps\Directories\Component\WordPressUser;

use SabaiApps\Directories\Component\AbstractComponent;
use SabaiApps\Directories\Component\Display;
use SabaiApps\Directories\Component\Entity;
use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Application;

class WordPressUserComponent extends AbstractComponent implements
	Entity\ITypes,
	Display\ILabels,
	Display\IElements,
	Display\IStatistics,
	Field\ITypes,
	Field\IWidgets {

	const VERSION = '2.0.6', PACKAGE = 'directories-pro';

	public static function description() {
		return 'Add and manage WordPress user profile fields and views.';
	}

	public function entityGetTypeNames() {
		return array( 'user' );
	}

	public function entityGetType( $name ) {
		switch ( $name ) {
			case 'user':
				return new EntityType\UserEntityType( $this->_application, $name );
		}
	}

	public function displayGetElementNames( Entity\Model\Bundle $bundle ) {
		return array( 'wordpressuser_comments' );
	}

	public function displayGetElement( $name ) {
		switch ( $name ) {
			case 'wordpressuser_comments':
				return new DisplayElement\UserCommentsDisplayElement( $this->_application, $name );
		}
	}

	public function displayGetLabelNames( Entity\Model\Bundle $bundle ) {
		return array( 'wordpressuser_role' );
	}

	public function displayGetLabel( $name ) {
		switch ( $name ) {
			case 'wordpressuser_role':
				return new DisplayLabel\UserRoleDisplayLabel( $this->_application, $name );
		}
	}

	public function fieldGetTypeNames() {
		return array( 'wordpressuser_role' );
	}

	public function fieldGetType( $name ) {
		switch ( $name ) {
			case 'wordpressuser_role':
				return new FieldType\UserRoleFieldType( $this->_application, $name );
		}
	}

	public function fieldGetWidgetNames() {
		return array( 'wordpressuser_role' );
	}

	public function fieldGetWidget( $name ) {
		switch ( $name ) {
			case 'wordpressuser_role':
				return new FieldWidget\UserRoleFieldWidget( $this->_application, $name );
		}
	}

	public function onCorePlatformWordPressInit() {
		add_filter( 'get_avatar', array( $this, 'getAvatarFilter' ), 1, 5 );
	}

	public function onCorePlatformWordPressAdminInit() {
		new AdminProfile( $this->_application );
	}

	public function getAvatarFilter( $avatar, $idOrEmail, $size, $default, $alt ) {
		if ( is_numeric( $idOrEmail ) ) {
			$id = (int) $idOrEmail;
		} elseif ( is_object( $idOrEmail ) ) {
			if ( $idOrEmail instanceof \WP_Comment ) {
				if ( $user = get_user_by( 'email', $idOrEmail->comment_author_email ) ) {
					$id = (int) $user->ID;
				}
			} elseif ( ! empty( $idOrEmail->ID ) ) {
				$id = (int) $idOrEmail->ID;
			}
		} elseif ( $user = get_user_by( 'email', $idOrEmail ) ) {
				$id = (int) $user->ID;
		}
		if ( ! empty( $id )
			&& ( $entity = $this->_application->Entity_Entity( 'user', $id ) )
			&& ( $url = $entity->getSingleFieldValue( 'user_photo', 'url' ) )
		) {
			$avatar = sprintf(
				'<img alt="%1$s" src="%2$s" class="avatar avatar-%3$s photo" height="%3$s" width="%3$s" />',
				$alt,
				$size > 48 ? $url['drts_icon_xl'] : $url['drts_icon_lg'],
				$size
			);
		}

		return $avatar;
	}

	public function onEntityCreateEntitySuccess( $bundle, $entity, $values, $extraArgs ) {
		if ( $bundle->type !== 'user__user'
			|| is_admin()
		) {
			return;
		}

		// Update WordPress user data
		$data   = array(
			'ID'          => $entity->getId(),
			'description' => $entity->getSingleFieldValue( 'user_description' ),
		);
		$result = wp_update_user( $data );
		if ( is_wp_error( $result ) ) {
			$this->_application->logError( 'Failed updating user data. Error: ' . $result->get_error_message() );
		}

		// Update user role?
		if ( ! empty( $values['wordpressuser_role'][0] ) ) {
			( new \WP_User( $entity->getId() ) )->set_role( $values['wordpressuser_role'][0] );
		}
	}

	public function onEntityUpdateEntitySuccess( $bundle, $entity, $oldEntity, $values, $extraArgs ) {
		$this->onEntityCreateEntitySuccess( $bundle, $entity, $values, $extraArgs );
	}

	public function displayGetStatisticNames( Entity\Model\Bundle $bundle ) {
		if ( $bundle->type !== 'user__user' ) {
			return array();
		}

		return array( 'wordpressuser_comments' );
	}

	public function displayGetStatistic( $name ) {
		return new DisplayStatistic\CommentCountDisplayStatistic( $this->_application, $name );
	}

	public function onFakerAdminGenerateTitleFilter( $title, $context, $bundle, $titleType ) {
		$this->_filterAdminTitle( $context, $bundle, $titleType );
	}

	public function onCsvAdminImportTitleFilter( $title, $context, $bundle, $titleType ) {
		$this->_filterAdminTitle( $context, $bundle, $titleType );
	}

	public function onCsvAdminExportTitleFilter( $title, $context, $bundle, $titleType ) {
		$this->_filterAdminTitle( $context, $bundle, $titleType );
	}

	public function onDirectoryAdminDirectorySendEmailTitleFilter( $title, $context, $bundle, $titleType ) {
		$this->_filterAdminTitle( $context, $bundle, $titleType );
	}

	public function onCalendarAdminOccurrencesTitleFilter( $title, $context, $bundle, $titleType ) {
		$this->_filterAdminTitle( $context, $bundle, $titleType );
	}

	protected function _filterAdminTitle( $context, $bundle, $titleType ) {
		if ( $titleType !== Application::ROUTE_TITLE_INFO
			|| $bundle->entitytype_name !== 'user'
		) {
			return;
		}

		$context->clearTabs()->clearMenus()->clearInfo()->setInfo( __( 'Users', 'directories-pro' ), admin_url( 'users.php' ) );
	}
}
