<?php

class WebUser extends CWebUser
{

    private $realUserInstance;
    private $sudoUserInstance;

    public function getRealUserId()
    {
        return $this->getState('realUserId');
    }

    public function getTranslateMode()
    {
        return $this->getState('translateMode');
    }

    public function getSudoUser()
    {
        return $this->getState('sudoUser');
    }

    public function getSudoUserInstance()
    {
        $sudoUserId = null;
        $sudoUserId = $this->getState('sudoUser');
        if (!$sudoUserId || $this->getRealUserId() == $sudoUserId) {
            return $this->getRealUserInstance();
        }

        if (!$this->sudoUserInstance) {
            $this->sudoUserInstance = User::model()->findByPk($sudoUserId);
        }

        return $this->sudoUserInstance;
    }

    public function getRealUserInstance()
    {
        if (!$this->realUserInstance) {
            $realUserId = $this->getState('realUserId');
            $this->realUserInstance = User::model()->findByPk($realUserId);
        }
        return $this->realUserInstance;
    }
    /* overwrites CWebUsers default init method, and this will
     * not be called cause of not starting a session
     * at this point for the openstage stuff
     */

    public function init()
    {
        CApplicationComponent::init();
        if (@$_REQUEST["r"] != "provisioningGeneral/default/siemens") {
            parent::init();
        }
    }

    public function setSuccessFlashMessage($message = 'CHANGES_SAVED_SUCCSESSFULLY')
    {
        Yii::app()->user->setFlash('success', '<strong>' . __($message) . '</strong>');
    }

    public function setErrorFlashMessage($message = 'CHANGES_NOT_SAVED_CAUSE_OF_AN_ERROR', $errors = array())
    {
        $completeMessage = '<strong>' . __($message) . '</strong>';

        if (!empty($errors)) {
            $formatedMsg = '<p>';
            foreach ($errors as $errorKey => $errorMsg) {
                $formatedMsg.= "$errorKey: " . __($errorMsg[0]) . "<br>";
            }
            $completeMessage = $completeMessage . $formatedMsg . '</p>';
        }
        Yii::app()->user->setFlash('error', $completeMessage);
    }
    
    public function login($identity, $duration = 0) 
    {
        if (function_exists("session_status") && session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
        parent::login($identity, $duration);
    }

}
