<?php 
class uniqueAuthName extends CValidator{

    /**
    * Validates the attribute of the object.
    * If there is any error, the error message is added to the object.
    * @param CModel $object the object being validated
    * @param string $attribute the attribute being validated
    */
    protected function validateAttribute($object,$attribute)
    {
        
        // extract the attribute value from it's model object
        $value=$object->$attribute; 
        if ($value === '') {

            return TRUE;
        } else  if (!$this->isOwnAuthName($object,$attribute, $value)) {

            if ($this->isExistingAuthName($value)) {
                $this->addError($object,$attribute, __('AUTHNAME_IS_UNIQUE_ERROR_MESSAGE'));
                return FALSE;
            }
        }
        return TRUE;
    }

    protected function isExistingAuthName($value) {
        
        /*if ($this->authnameexsists('Gateway',$value)) {
            return TRUE;
        }*/

        if ($this->authnameexsists('SipAccounts',$value)) {
            return TRUE;
        }
 
        require_once(__DIR__.'/../../modules/routingExternalHost/models/ExternalHost.php');
        if ($this->authnameexsists('ExternalHost',$value,'username')) {
            return TRUE;
        }
        return FALSE;
    }

    protected function authnameexsists($modelName,$value,$attribute='authname') {
        
        $model = $modelName::model()->findByAttributes(array($attribute=>$value));
        if ($model) {
            return TRUE;
        } 
        return FALSE;
    }
    
    protected function isOwnAuthName($object,$attribute, $value) {

        if ($object->isNewRecord()) {
            return false;
        } else {

            $result = $object->findAllByAttributes(array($attribute=>$value));
            if (empty($result)) {
                return false;
            } else {
                $result = $result[0];
                if ($result->id == $object->id) {
                    return true;
                }
            }
        }
        return false;
    }
}