<?php

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

/**
 * Description of inlineeditor_autoload
 *
 * @author Igor Ratsun
 */
class inlineeditor_autoload
{

    public function __construct()
    {
        $ci = & get_instance();

        // Disable in admin panel
        $adminLink = base_url($ci->config->item('admin_page'));
        $curLink = base_url($ci->uri->uri_string());
        if (strpos($curLink, $adminLink) !== FALSE) {

            return TRUE;
        }

        $ci->load->library(array(
            'ciext/configurator',
            'ciext/RT_user'
        ));

        // Acceess check
        if (!$ci->rt_user->isAllowed('inlineeditor', 'edit_inlineeditor')) {

            return TRUE;
        }

        $cnf = new configurator();
        $cnf->set_resource('inlineeditor');
        $config = $cnf->get_config();
        $dialog = '';
        if (!empty($config['show_editor'])) {
            $ci->load->model('ciext/core_model');
            $ci->core_model->add_callback(Core_model::CALLBACK_PARSE_RESOURCE, array($this, 'callback_parse_resource'));

            $dialog = $this->prepare_str($ci->parser->parse('inlineeditor/dialog', array(), TRUE));
        }

        $ci->load->library('gettext_language');
        $ci->gettext_language->load(__DIR__ . '/../language/' . $ci->config->item('language') . '.po');
        
        $dialog .= $this->prepare_str($ci->parser->parse('inlineeditor/buttons', array('show_editor' => (int) $cnf->item('show_editor')), TRUE));
        $ci->load->library('ciext/ciext')->load_jquery();
        $ci->js_css->parse_js('inlineeditor/js/main.js', array(
            'dialog' => $dialog,
            'id_lan' => $ci->load->library('db_lang_lib')->get_current_lang_id(),
        ));
        $ci->js_css->parse_css('inlineeditor/css/main.css');
    }

    public function callback_parse_resource($data, $id_resource, $attr = array())
    {
        $rs = $data;
        if (empty($attr['inlineeditor']) || $attr['inlineeditor'] != 'off') {
            $ci = & get_instance();

            // Add attributes
            $dataAttr = array(
                array(
                    'key' => 'id',
                    'val' => $id_resource,
                )
            );
            foreach ($attr as $key => $val) {
                if ($key == 'inlineeditor' || $key == 'id') {
                    continue;
                }
                $dataAttr[] = array(
                    'key' => $key,
                    'val' => $val,
                );
            }

            $rs = $ci->parser->parse('inlineeditor/inline_container', array(
                'content'  => $data,
                'dataAttr' => $dataAttr
                    ), TRUE
            );
        }

        return $rs;
    }

    protected function prepare_str($str = '')
    {
        return trim(preg_replace('/\s+/', ' ', $str));
    }
}
