<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {

    /**
     * Authenticates a user.
     * The example implementation makes sure if the username and password
     * are both 'demo'.
     * In practical applications, this should be changed to authenticate
     * against some persistent user identity storage (e.g. database).
     * @return boolean whether authentication succeeds.
     */
    private $_id;
    private $userMonitor = false;
    private $realUserId = null;
    private $sudoUser = null;

    public function authenticate() {

        $count = User::model()->count();
        $user = null;

        Yii::log("user " . $this->username . " tries to login", "verbose", "auth");
        if ($count != "0") {

            $user = User::model()->findByAttributes(array('name' => $this->username));
            if ($user != NULL) {
                $this->_id = $user->getPrimaryKey();
                $this->userMonitor = $user->userMonitor ? $user->userMonitor : 'false';
            } else {
                $this->errorCode = self::ERROR_USERNAME_INVALID;
                return $this->errorCode;
            }
        } else {

            $initializer = new PhonalisaInitializer();
            if ($initializer->runInit() === true) {
                $user = $initializer->getDefaultAdminUser();
                $this->userMonitor = 'false';
                $this->_id = $user->getPrimaryKey();
            }
        }

        if (!isset($user->name)) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if ($user->name !== $this->username) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if ($user->password !== md5($this->password . $this->_id)) {

            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else {

            $lang = $user->getDefaultLanguage();
            if ($lang == 'Default Language') {
                $lang = cfg('GUI_LANGS');
            }
            Yii::app()->user->setState('language', $lang);



            // $this->setState('mainSections', $mainSections);

            $this->setState('realUserId', $this->_id);
            $this->setState('sudoUser', $this->_id);
            if (cfg("WEB_USER_MONITOR_ENABLED")) {
                $this->setState('userMonitor', $this->userMonitor);
            } else {
                $this->setState('userMonitor', "false");
            }

            $this->setState(
                    'translateMode', cfg('TRANSLATE_MODE') === '1' ? true : false
            );

            $this->errorCode = self::ERROR_NONE;
        }

        return !$this->errorCode;
    }

    public function getId() {
        return $this->_id;
    }

}
