<?php
namespace SabaiApps\Directories\Helper;

use SabaiApps\Directories\Application;

/**
 * InstalledComponentsHelper class for retrieving installed components.
 * Returns an array of installed components with version, config, and events.
 */
class InstalledComponentsHelper {

	/**
	 * Gets installed components, optionally forcing a reload.
	 *
	 * @param Application $application
	 * @param bool        $force
	 * @return array
	 */
	public function help( Application $application, $force = false ) {
		if ( $force || ( false === $ret = $application->getPlatform()->getCache( 'core_components_installed' ) ) ) {
			$ret = array();
			try {
				$components = $application->fetchComponent( 'System' )->getModel( 'Component' )->fetch( 0, 0, 'priority', 'DESC' );
				foreach ( $components as $component ) {
					$events = array();
					if ( $component->events ) {
						$default_event_priority = $component->name === 'System' ? 99 : 10;
						foreach ( (array) $component->events as $event ) {
							if ( ! is_array( $event ) ) {
								$event = array( $event );
							}
							$events[] = array( strtolower( $event[0] ), isset( $event[1] ) ? $event[1] : $default_event_priority );
						}
					}
					$ret[ $component->name ] = array(
						'version' => $component->version,
						'config'  => $component->config ?: array(),
						'events'  => $events,
					);
				}
			} catch ( \Exception $e ) {
				// Probably application has not been installed yet
				$application->logError( $e );
			}
			$application->getPlatform()->setCache( $ret, 'core_components_installed' );
		}

		return $ret;
	}
}
