<?php
namespace SabaiApps\Directories\Helper;

use SabaiApps\Directories\Application;

/**
 * InstalledComponentsByInterfaceHelper class for listing installed components by interface.
 * Returns an array of component names that implement a given interface.
 */
class InstalledComponentsByInterfaceHelper {

	protected $_interfaces;

	/**
	 * Gets installed components by interface.
	 *
	 * @param Application $application
	 * @param string|null $interface Interface name.
	 * @param bool        $force Force reload.
	 * @return array
	 */
	public function help( Application $application, $interface, $force = false ) {
		$interfaces = $this->_getInterfaces( $application, $force );

		if ( ! isset( $interface ) ) {
			return $interfaces;
		}

		return isset( $interfaces[ $interface ] ) ? array_keys( $interfaces[ $interface ] ) : array();
	}

	/**
	 * Loads and caches interfaces implemented by installed components.
	 *
	 * @param Application $application
	 * @param bool        $force
	 * @return array
	 */
	protected function _getInterfaces( Application $application, $force ) {
		if ( ! isset( $this->_interfaces )
			|| $force
		) {
			$local             = $application->LocalComponents( $force );
			$components        = $application->InstalledComponents( $force );
			$this->_interfaces = array();
			foreach ( array_keys( $components ) as $component_name ) {
				if ( ! empty( $local[ $component_name ]['interfaces'] ) ) {
					foreach ( $local[ $component_name ]['interfaces'] as $interface ) {
						$this->_interfaces[ $interface ][ $component_name ] = true;
					}
				}
			}
		}
		return $this->_interfaces;
	}
}
