<?php

class WebUser extends CWebUser {

    /**
     * @var boolean whether to enable cookie-based login. Defaults to false.
     */
    public $allowAutoLogin = true;

    /**
     * @var string|array the URL for login. If using array, the first element should be
     * the route to the login action, and the rest name-value pairs are GET parameters
     * to construct the login URL (e.g. array('/site/login')). If this property is null,
     * a 403 HTTP exception will be raised instead.
     * @see CController::createUrl
     */
    public $loginUrl = array('/usuario/login');

    public function getRole() {
        return $this->getState('__role');
    }

    public function getId() {
        return $this->getState('__id') ? $this->getState('__id') : 0;
    }

//    protected function beforeLogin($id, $states, $fromCookie)
//    {
//        parent::beforeLogin($id, $states, $fromCookie);
//
//        $model = new UserLoginStats();
//        $model->attributes = array(
//            'user_id' => $id,
//            'ip' => ip2long(Yii::app()->request->getUserHostAddress())
//        );
//        $model->save();
//
//        return true;
//    }

    protected function afterLogin($fromCookie) {
        parent::afterLogin($fromCookie);
        $this->updateSession();
    }

    public function updateSession() {
        $usuario = Yii::app()->getModule('usuario')->usuario($this->id);
        
        $this->name = $usuario->username;
        
        $userAttributes = CMap::mergeArray(array(
                'email' => $usuario->email,
                'username' => $usuario->username,
                'fecha_registro' => $usuario->fecha_registro,
                'ultima_visita' => $usuario->ultima_visita,
            ), $usuario->perfil->getAttributes());

        foreach ($userAttributes as $attrName => $attrValue) {
            $this->setState($attrName, $attrValue);
        }
    }

    public function model($id = 0) {
        return Yii::app()->getModule('usuario')->usuario($id);
    }

    public function user($id = 0) {
        return $this->model($id);
    }

    public function getUserByName($username) {
        return Yii::app()->getModule('usuario')->getUserByName($username);
    }

    public function getAdmins() {
        return Yii::app()->getModule('usuario')->getAdmins();
    }

    public function isAdmin() {
        return Yii::app()->getModule('usuario')->isAdmin();
    }

}