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

use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Application;

class ParentIdFieldType extends AbstractParentFieldType implements
	Field\Type\IQueryable {

	use QueryableIdTrait {
		fieldQueryableInfo as traitFieldQueryableInfo;
	}

	public function fieldTypeSchema( array $settings = array() ) {
		return array(
			'columns' => array(
				'value' => array(
					'type'     => Application::COLUMN_INTEGER,
					'notnull'  => true,
					'unsigned' => true,
					'was'      => 'value',
					'default'  => 0,
				),
			),
		);
	}

	public function fieldTypeOnSaveValues( Field\IField $field, array $values, ?array $currentValues = null, array &$extraArgs = array() ) {
		$ret = array();
		foreach ( $values as $weight => $value ) {
			if ( strlen( (string) $value ) === 0 ) {
				continue;
			}

			$ret[]['value'] = $value;
			break;
		}
		return $ret;
	}

	public function fieldQueryableInfo( Field\IField $field, $inAdmin = false ) {
		$info = $this->traitFieldQueryableInfo( $field, $inAdmin );
		if ( $inAdmin ) {
			$info['tip'] = __( 'Enter IDs or "_current_" (for current parent post) separated with commas. Prefix with "-" to exclude, e.g. -2,-10,-_current_.', 'directories-pro' );
		}
		return $info;
	}

	protected function _getCurrentEntityId() {
		return ( $entity = $this->_getCurrentEntity() ) && ( $parent_entity = $this->_application->Entity_ParentEntity( $entity ) ) ? $parent_entity->getId() : null;
	}
}
