<?php

/**
 * Description of LanguageParser
 *
 * @author NE
 */
class RCMS_Object_Parser_LanguageParser {
	
	const LANG_FILE_EXTENSION = 'lng';

	protected $_model = null;

	protected $_languageId = '';

	private $_configData = array();

	private $_content = '';

	private $_langFile = null;

	private $_langFilePath = '';

	private $_langMap = array();

	public function  __construct($languageId = '') {
		$this->_model = new RCMS_Object_Parser_LanguageParserModel();
		$this->_configData = $this->_model->selectAllConfigData();
		$this->_languageId = (!$languageId) ? $this->_configData['translate_language'] : $languageId;
		$this->_langFile = $this->_languageId . '.' . self::LANG_FILE_EXTENSION;
		$this->_langFilePath = unserialize(Zend_Registry::get('config'))->website->website->path . 'public/downloads/' . $this->_langFile;
		$langFileContent = @file_get_contents($this->_langFilePath);
		if(!$langFileContent) {
			return;
		}
		else {
			$this->_langMap = eval(RCMS_Tools_Tools::stripSlashesIfQuotesOn(file_get_contents($this->_langFilePath)));
		}
	}

	public function processScreen($content) {
		$this->_content = trim($content);
		$this->_parse();
		return $this->_content;
	}

	private function _parse() {
		$lexems = $this->_findLexems();
		if(empty ($lexems)) {
			return;
		}
		foreach ($lexems as $lexem) {
			$replacement = $this->_getTranslatedValue($lexem);
			$this->_replaceLexems($lexem, $replacement);
		}
		$this->_parse();
	}

	/**
	 * Find lexems for multilang.
	 *
	 * @return array
	 */
	private function _findLexems() {
        preg_match_all('/{%([^%}]+)%}/', $this->_content, $found);
		return $found[1];
	}

	private function _getTranslatedValue($lexem) {
		if(isset($this->_langMap['{%' . $lexem .'%}'])) {
			$translation = $this->_langMap['{%' . $lexem .'%}'];
		}
		else {
			$translation = $lexem;
		}
		return $translation;
	}

	public function setContent($content) {
		$this->_content = trim($content);
	}

	public function getContent() {
		return $this->_content;
	}

	/**
	 * Replace system varriables
	 *
	 * @param string $variable
	 * @param string $replace
	 */
	private function _replaceLexems($lexem, $replace) {
		$pattern = '/(<.* value=\")({%' . preg_replace('/([\/\\\]){1}/', '\$1', $lexem) . '%})(\".*>)/i';
		$replacement = "\${1}$replace\$3";
		$this->_content = preg_replace($pattern, $replacement, $this->_content);

		$pattern = '/(<button.*>)({%' . preg_replace('/([\/\\\]){1}/', '\$1', $lexem) . '%})(<\/button>)/i';
		$replacement = "\${1}$replace\$3" ;
		$this->_content = preg_replace($pattern, $replacement, $this->_content);

		$pattern = '/(<a.*>)({%' . preg_replace('/([\/\\\]){1}/', '\$1', $lexem) . '%})(<\/a>)/i';
		$replacement = "\${1}$replace\$3";
		$this->_content = preg_replace($pattern, $replacement, $this->_content);
		$this->_content = str_replace('{%' . $lexem . '%}', $replace, $this->_content);
	}

}
