<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Description of gettext_language
 *
 * @author Igor Ratsun
 */
class Gettext_language
{

    public function __construct($language = NULL)
    {
        $CI = & get_instance();
        if (is_null($language)) {
            $langs = $CI->config->item('allowed_language');
            $language = (isset($langs[$CI->uri->current_language])) ? $langs[$CI->uri->current_language] : $CI->config->item('language');
        }

        // Default file path
        $file = FCPATH . 'application' . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR . $language . '.po';

        $this->load($file);
    }

    /**
     * Load data from .po file
     * @param string $file - .po file
     */
    public function load($file)
    {
        $rs = array();
        if (file_exists($file)) {
            $fileStr = str_replace('"' . PHP_EOL . '"', '', file_get_contents($file));
            $items = array();
            preg_match_all('/msgid\s\"(.*)\"\nmsgstr\s\"(.*)\"/', $fileStr, $items);
            if (!empty($items[1]) && !empty($items[2]) && count($items[1]) == count($items[2])) {
                foreach (array_combine($items[1], $items[2]) as $k => $v) {
                    if (!empty($k) && !empty($v)) {
                        $rs[$k] = $v;
                    }
                }
            }
        }

        $CI = & get_instance();
        $CI->lang->language = array_merge($CI->lang->language, $rs);
    }

}
