<?php

class Inline_text
{
    private $ci;
    private $admin_segment = 'text';

    public function __construct()
    {
        $this->ci = get_instance();
        $this->ci->load->model('inlineeditor/inlineeditor_text_tmodel');
        $this->ci->load->library('inlineeditor/inline_base');
    }

    public function parse($text, $i_id = null)
    {
        $text = trim($text);
        $i_id = empty($i_id) ? $this->ci->inlineeditor_text_tmodel->create_i_id($text) : $i_id;

        // Create and redirect if needed
        if ($this->show_edit() && $this->ci->input->get('inline_create') == $i_id) {
            $id = $this->ci->inlineeditor_text_tmodel->add_value($text);
            redirect($this->generate_url($id));
        }

        $value = $this->ci->inlineeditor_text_tmodel->get_value_by_i_id($i_id);
        $result = !empty($value['value']) ? $value['value'] : $text;

        // Process parsers
        $result = $this->ci->load->library('ciext/parser/ciext_parser')->parse($result);

        if ($this->show_edit()) {
            $url = empty($value['id']) ? '?inline_create=' . $i_id : $this->generate_url($value['id']);
            $result .= $this->ci->inline_base->admin_link($url);
        }

        return $result;
    }

    public function set_admin_segment($admin_segment)
    {
        $this->admin_segment = $admin_segment;
        return $this;
    }

    protected function show_edit()
    {
        return $this->ci->inline_base->show_edit();
    }

    protected function generate_url($id)
    {
        return $this->ci->inline_base->generate_url($id, $this->admin_segment);
    }
}