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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Component\Entity\Type\IEntity;
use SabaiApps\Directories\Exception\InvalidArgumentException;

class UtilHelper {

	public function syncTerms( Application $application, $entity, $taxonomy = null, array $extraArgs = array() ) {
		if ( ! $entity instanceof IEntity ) {
			if ( ! $entity = $application->Entity_Entity( 'post', $entity ) ) {
				return;
			}
		}
		if ( ( ! $bundle = $application->Entity_Bundle( $entity ) )
			|| empty( $bundle->info['taxonomies'] )
		) {
			return;
		}

		if ( isset( $taxonomy ) ) {
			if ( ! $bundle_type = array_search( $taxonomy, $bundle->info['taxonomies'] ) ) {
				throw new InvalidArgumentException( 'Invalid taxonomy: ' . $taxonomy );
			}
			$taxonomies = array( $bundle_type => $taxonomy );
		} else {
			$taxonomies = $bundle->info['taxonomies'];
		}
		$values = array();
		foreach ( $taxonomies as $bundle_type => $taxonomy ) {
			$term_ids = wp_get_object_terms( $entity->getId(), $taxonomy, array( 'fields' => 'ids' ) );
			if ( ! is_array( $term_ids ) ) {
				continue;
			}

			$values[ $bundle_type ] = $term_ids;
		}
		$application->Entity_Save( $entity, $values, $extraArgs );
	}

	public function maybeSetPostThumbnail( Application $application, Bundle $bundle, IEntity $entity, $unassign = false, $ignoreAuto = false ) {
		if ( $unassign ) {
			delete_post_thumbnail( $entity->getId() );
			return;
		}

		if ( ! post_type_supports( $bundle->name, 'thumbnail' )
			|| empty( $bundle->info['wp_post_thumbnail'] )
			|| ( ! $ignoreAuto && empty( $bundle->info['wp_post_thumbnail_auto'] ) )
			|| empty( $bundle->info['entity_image'] )
		) {
			return;
		}

		delete_post_thumbnail( $entity->getId() );
		if ( $value = $entity->getSingleFieldValue( $application->Filter( 'wordpresscontent_post_thumbnail_field', $bundle->info['entity_image'], array( $entity ) ) ) ) {
			set_post_thumbnail( $entity->getId(), $value['attachment_id'] );
		}
	}

	public function maybeSetTermThumbnail( Application $application, Bundle $bundle, IEntity $entity, $unassign = false ) {
		if ( $unassign ) {
			delete_term_meta( $entity->getId(), 'thumbnail_id' );
			return;
		}

		if ( empty( $bundle->info['wp_term_thumbnail'] )
			|| empty( $bundle->info['entity_image'] )
		) {
			return;
		}

		delete_term_meta( $entity->getId(), 'thumbnail_id' );
		if ( $value = $entity->getSingleFieldValue( $application->Filter( 'wordpresscontent_term_thumbnail_field', $bundle->info['entity_image'], array( $entity ) ) ) ) {
			update_term_meta( $entity->getId(), 'thumbnail_id', $value['attachment_id'] );
		}
	}
}
