<?php

/**
 * Description of MessagesFileHelper
 *
 * @author Mohammed Osman  <osmancode@gmail.com>
 */
class MessagesFileHelper {

    public $_path = '';
    public $_languages = array();

    public function __construct($path, $relative = false) {
        if ($relative == true) {
            $path = Yii::app()->basePath . $path;
        }
        $this->_path = $path;
    }

    public function getFinalData() {
        $finalData = array();
        $files = glob($this->_path . '/*.php');
        if ($files) {
            foreach ($files as $file) {
                $finalData['path'] = str_replace(Yii::app()->basePath, '', $this->_path);
                $finalData['file'] = str_replace(Yii::app()->basePath, '', $file);
                $finalData['filename'] = str_replace($this->_path . '/', '', $file);
                $language = false;
                $parts = explode('/', str_replace("\\", '/', $this->_path));
                if (end($parts)) {
                    $language = end($parts);
                }
                $finalData['language'] = $language;
                $finalData['languageLabel'] = Yii::app()->locale->getLanguage($language);
//		$finalData['data'] = require $file;
            }
        }
        return $finalData;
    }

    public static function getMessagesDirs() {
        $basePath = Yii::app()->basePath . DIRECTORY_SEPARATOR . '*';
        $dirs = self::glob_recursive($basePath, GLOB_ONLYDIR);
        $messagesDir = array();
        foreach ($dirs as $value) {
            if (preg_match('/(\/messages\/)([a-z]{2})(_[a-z]{2})?$/', $value)) {
                $messagesDir[] = $value;
            }
        }
        return $messagesDir;
    }

    /**
     * 
     * @param type $pattern
     * @param type $flags Does not support flag GLOB_BRACE
     * @return type
     */
    private static function glob_recursive($pattern, $flags = 0) {
        $files = glob($pattern, $flags);
        foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
            // exclude vendors dir
            $endsWith = substr_compare($dir, 'vendor', -strlen('vendor')) === 0 || substr_compare($dir, 'vendors', -strlen('vendors')) === 0;
            if ($endsWith)
                return $files;
            $files = array_merge($files, self::glob_recursive($dir . '/' . basename($pattern), $flags));
        }
        return $files;
    }

    public function getLanguage() {
        $language = str_replace('\\', '/', $this->_path);
        $parts = explode('/', $language);
        array_pop($parts);
        if (preg_match('/([a-z]{2})(_[a-z]{2})?$/', end($parts))) {
            return end($parts);
        }
        return false;
    }

}
