<?php

class Fiktiv_Highlighter {

    protected $_highlighter = null;

    protected $_regex = '/<code lang\=\"([A-Za-z]+)\">(.+)<\/code>/imsU';

    public function setHighlighter($highlighter) {

        $class = 'Fiktiv_Highlighter_'.ucfirst($highlighter);
        
        if (is_string($highlighter) && class_exists($class)) {
            $highlighter = new $class;
        }

        if ($highlighter instanceof Fiktiv_Highlighter_Abstract) {
            $this->_highlighter = $highlighter;
        }
        
    }

    public function getHighlighter() {
    
        if (null === $this->_highlighter) {
            throw new Fiktiv_Highlight_Exception('no highlighter specified');
        }

        return $this->_highlighter;
    }

    public function replaceCodeblock($block)
    {
        preg_match_all($this->_regex, $block, $code);
        
        if ($code[1]) {

            foreach ($code[1] as $key => $lang) {
                $c = str_replace('<br>', "\n",html_entity_decode($code[2][$key], ENT_COMPAT,'UTF-8'));
                $block = str_replace($code[2][$key], $this->highlight($c, $lang), $block);
            }

        }
        return $block;
    }

    public function highlight($code, $lang = null, $options = array()) {

        return $this->getHighlighter()->highlight($code, $lang, $options);
    }

    public function __call($name, $args)
    {
        if (method_exists($this->_highlighter, $name)) {
            call_user_func(array($this->_highlighter, $name), $args);
        }
    }

}
