<?php
namespace SabaiApps\Directories\Component\Entity\FieldType;

use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Component\Field\IField;
use SabaiApps\Directories\Component\Field\Type\AbstractValueType;
use SabaiApps\Directories\Component\Field\Type\IColumnable;
use SabaiApps\Directories\Component\Field\Type\IRestrictable;

class LevelFieldType extends AbstractValueType implements IRestrictable, IColumnable {

	protected function _fieldTypeInfo() {
		return array(
			'label'       => __( 'Feature level', 'directories-pro' ),
			'icon'        => 'fab fa-level-up-alt',
			'schema_type' => 'string',
			'admin_only'  => true,
		);
	}

	protected function _onSaveValue( IField $field, $value, array $settings, $key ) {
		$value = trim( (string) $value );
		return $value === 'default' ? null : $value;
	}

	public function fieldRestrictableOptions( IField $field ) {
		if ( ( ! $bundle = $field->Bundle )
			|| ( ! $options = $this->_application->Entity_Levels_options( $bundle, false ) )
		) {
			return;
		}

		return array( 'value' => $options );
	}

	public function fieldRestrictableRestrict( IField $field, $value, $name ) {}

	public function fieldHumanReadableText( IField $field, IEntity $entity, $separator = null, $key = null ) {
		if ( ( ! $value = $entity->getSingleFieldValue( $field->getFieldName() ) )
			|| ( ! $bundle = $field->Bundle )
			|| empty( $bundle->info['entity_level'] )
			|| empty( $bundle->info['entity_levels'][ $value ] )
		) {
			return;
		}

		return $bundle->info['entity_levels'][ $value ]['label'];
	}

	public function fieldCopyValues( IField $field, array $values, array &$allValue, $lang = null ) {
		return $values;
	}

	public function fieldColumnableInfo( IField $field ) {
		if ( ( ! $bundle = $field->Bundle )
			|| empty( $bundle->info['entity_levels'] )
		) {
			return;
		}

		return array(
			'' => array(
				'label'  => $field->getFieldLabel(),
				'sortby' => 'value',
				'hidden' => true,
			),
		);
	}

	public function fieldColumnableColumn( IField $field, IEntity $entity, $column = '' ) {
		if ( ( ! $values = $entity->getFieldValue( $field->getFieldName() ) )
			|| empty( $values[0] )
			|| ( ! $bundle = $field->Bundle )
			|| empty( $bundle->info['entity_levels'][ $values[0] ] )
		) {
			return;
		}

		return $bundle->info['entity_levels'][ $values[0] ]['label'];
	}
}
