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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Type\IEntity;

class ParentEntityHelper {

	public function help( Application $application, IEntity $entity, $loadEntityFieldValues = true ) {
		if ( ! $entity->isFieldsLoaded() ) {
			$application->Entity_Field_load( $entity );
		}
		if ( ! $bundle = $application->Entity_Bundle( $entity ) ) {
			return;
		}

		if ( ! $parent_id = $entity->getParentId() ) {
			if ( empty( $bundle->info['parent_field'] )
				|| ( ! $parent_field = $entity->getSingleFieldValue( $bundle->info['parent_field'] === true ? 'entity_parent' : $bundle->info['parent_field'] ) )
			) {
				return;
			}

			$parent_id   = $parent_field['parent_entity_id'];
			$parent_type = $parent_field['parent_entity_type'];
		} elseif ( ! empty( $bundle->info['parent'] ) ) {
			if ( ! $parent_bundle = $application->Entity_Bundle( $bundle->info['parent'] ) ) {
				return;
			}

				$parent_type = $parent_bundle->entitytype_name;
		} elseif ( ! empty( $bundle->info['parent_field'] ) ) {
			if ( ! $parent_field = $entity->getSingleFieldValue( $bundle->info['parent_field'] === true ? 'entity_parent' : $bundle->info['parent_field'] ) ) {
				return;
			}

			$parent_type = $parent_field['parent_entity_type'];
		}

		if ( empty( $parent_type )
			|| empty( $parent_id )
			|| ( ! $parent = $application->Entity_Entity( $parent_type, $parent_id, false ) )
		) {
			return;
		}

		$entity->setParent( $parent );

		if ( $loadEntityFieldValues ) {
			$application->Entity_Field_load( $parent );
		}

		return $parent;
	}
}
