<?php
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage View
 * @since 2010-03-09
 */

class MsgViewHelper extends ViewHelper
{

    const SUCCESS = 'success';

    const ERROR = 'error';

    const INFO = 'info';

    const WARNING = 'warning';

    protected $css_prefix = '';

    public function msg($msg = null, $type = null)
    {
        if ($msg && $type) {
            if (!in_array($type, array(self::SUCCESS, self::ERROR, self::INFO, self::WARNING))) {
                throw new GeneralException('Unknown message type: "' . $type . '"');
            }
            $this->set($msg, $type);
        }
        return $this;
    }

    public function success($msg)
    {
        $this->set($msg, self::SUCCESS);
    }

    public function error($msg)
    {
        $this->set($msg, self::ERROR);
    }

    public function info($msg)
    {
        $this->set($msg, self::INFO);
    }

    public function warning($msg)
    {
        $this->set($msg, self::WARNING);
    }

    protected function set($msg, $type)
    {
        Session::set(__CLASS__, array('message' => $msg, 'type' => $type));
    }

    public function withPrefix($css_prefix)
    {
        $this->css_prefix = $css_prefix;
        return $this;
    }

    public function __toString()
    {
        $msg = Session::get(__CLASS__, false);
        if ($msg) {
            Session::del(__CLASS__);
            return '<div class="' . $this->css_prefix . $msg['type'] . '">' . $this->view->escape($msg['message']) . '</div>';
        }
        return '';
    }
}