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

use SabaiApps\Directories\Application;
use SabaiApps\Directories\Component\Payment\Component\IComponent;
use SabaiApps\Directories\Exception;

class ComponentsHelper {

	public function help( Application $application, $useCache = true ) {
		if ( ! $useCache
			|| ( ! $components = $application->getPlatform()->getCache( 'payment_components' ) )
		) {
			$components = array();
			foreach ( $application->InstalledComponentsByInterface( 'Payment\IComponents' ) as $component_name ) {
				if ( ! $application->isComponentLoaded( $component_name ) ) {
					continue;
				}

				foreach ( $application->getComponent( $component_name )->paymentGetComponentNames() as $payment_component_name ) {
					if ( ! $component = $application->getComponent( $component_name )->paymentGetComponent( $payment_component_name ) ) {
						continue;
					}

					$components[ $payment_component_name ] = $component_name;
				}
			}
			$application->getPlatform()->setCache( $components, 'payment_components' );
		}

		return $components;
	}

	private $_impls = array();

	/**
	 * @param Application $application
	 * @param string      $component
	 * @return IComponent
	 */
	public function impl( Application $application, $component, $returnFalse = false ) {
		if ( ! isset( $this->_impls[ $component ] ) ) {
			if ( ( ! $components = $application->Payment_Components() )
				|| ! isset( $components[ $component ] )
				|| ! $application->isComponentLoaded( $components[ $component ] )
			) {
				if ( $returnFalse ) {
					return false;
				}
				throw new Exception\UnexpectedValueException( sprintf( 'Invalid payment component: %s', $component ) );
			}
			$this->_impls[ $component ] = $application->getComponent( $components[ $component ] )->paymentGetComponent( $component );
		}

		return $this->_impls[ $component ];
	}
}
