<?php

// TODO: the loader for langs should work only for the exact location as in the local module; now it does a lcfirst to keep compatibility with the nonMVC modules


namespace App;

// TODO when TINA lang dirs will have a clean structure, this class contents can be deleted

/**
 * The class manages the loading of the lang files.
 * @author Dan
 */
class Loader_Lang extends \Engine\Loader_Lang
{

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Loader_Lang::loadSection()
	 */
	public function loadSection($section)
	{
		// determine if it is an app section or plugin
		if (substr($section, 0, 8) == 'Modules/') {
			$realSection = substr($section, 8);  // remove "Modules/"
			return $this->loadAppSection($realSection);
		}
		elseif (substr($section, 0, 8) == 'Plugins/' || substr($section, 0, 8) == 'plugins/') {
			$realSection = lcfirst($section);   // TINA has plugins folder with lowercase first letter
			return $this->loadPluginSection($realSection);
		}
		else {
			$realSection = $section; // old modules
			return $this->loadAppFolder($realSection);
		}

	}

	/**
	 * alter $section to be compatible with TINA file structure (lowercase first dir char, no parent Modules/ lang dir)
	 * TODO when TINA lang dirs will have a clean structure, this function can be deleted from this file
	 * @see \Engine\Loader_Lang::loadAppSection()
	 */
	public function loadAppSection($section)
	{
		// convert "Admin/Users/CreateUser" to "admin/users/createUser"
		$sectionArr = explode("/", $section);
		foreach ($sectionArr as $idx=>$piece) {
			$sectionArr[$idx] = lcfirst($piece);
		}

		$section = implode("/", $sectionArr);

		return parent::loadAppSection($section);
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Loader_Lang::loadPluginSection()
	 */
	public function loadPluginSection($section)
	{
		return parent::loadPluginSection(lcfirst($section));
	}


	/**
	 * (non-PHPdoc)
	 * @see \Engine\Loader_Lang::loadPluginFile()
	 */
	public function loadPluginFile($pluginNamespace, $fileName)
	{
		$pluginNamespace = ltrim($pluginNamespace, "\\/");
		parent::loadPluginFile(lcfirst($pluginNamespace), $fileName);
		return $this;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Loader_Lang::loadFileFromAllPlugins()
	 */
	public function loadFileFromAllPlugins($fileName)
	{
		$pluginsDir = APP_REAL_PATH.'plugins/';

		$dirs = \Engine\Dir::getContents($pluginsDir, 'dir');

		foreach ($dirs as $dir) {
			$this->loadPluginFile("plugins/".$dir, $fileName);
		}

		return $this;
	}


	/**
	 * (non-PHPdoc)
	 * @see \Engine\Loader_Lang::getSection()
	 */
	public function getSection($section)
	{
		if (substr($section, 0, 8) == 'Modules/') {
			$section = substr($section, 8);
		}

		return parent::getSection($section);
	}


}
