<?php

namespace WpieFw\Modules;

use WpieFw\Files\WpieFile;
use WpieFw\Wpie\WpieGlobals;
use WpieFw\Helpers\WpieMiscHelper;
use WpieFw\Modules\Iterator\WpieModule;
use WpieFw\Modules\WpieModulesFactory;
use WpieFw\Modules\WpieModulesBuilderInterface;
use WpieFw\Settings\WpieSettingsProcessor;

if( ! defined( 'ABSPATH' ) ) exit;

final class WpieModulesBuilder implements WpieModulesBuilderInterface
{
	/**
	 * @var WpieModulesFactory
	 */
	private $factory;

	/**
	 * @var WpieModule
	 */
	private $module = null;

	/**
	 * Constructor
	 *
	 * @param WpieModulesFactory $factory
	 */
	public function __construct( WpieModulesFactory $factory )
	{
		$this->factory = $factory;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::instance()
	 */
	public function instance( WpieFile $file )
	{
		$baseName = $file->getBaseName( '.' . $file->getExtension() );

		// the class name based on the module's file name and the plugins namespace
		$className = WpieMiscHelper::hyphenToCamel( $baseName );

		// let the Modules factory create an instance
		$this->module = $this->factory->create( $className );

		return $this->module;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::setPath()
	 */
	public function setPath( $path = '' )
	{
		$this->module->setPath( $path );

		return $this;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::setVars()
	 */
	public function setVars( array $vars )
	{
		$this->module->setVars( $vars );

		return $this;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::setIndex()
	 */
	public function setIndex( $index = '' )
	{
		$this->module->setIndex( $index );

		return $this;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::setGlobals()
	 */
	public function setGlobals( WpieGlobals $globals )
	{
		$this->module->setGlobals( $globals );

		return $this;
	}

	/**
	 * {@inheritDoc}
	 * @see \WpieFw\Modules\WpieModulesBuilderInterface::setSettingsProcessor()
	 */
	public function setSettingsProcessor( WpieSettingsProcessor $processor )
	{
		$this->module->setSettingsProcessor( $processor );

		return $this;
	}
}