<?php

class Todojsc_Service_Authentication
{
    protected $_authAdapter;
    protected $_userModel;
    protected $_auth;

    public function __construct(Todojsc_Model_Users $model = null)
    {
        $this->_userModel = null === $model ? new Todojsc_Model_Users() : $model;
    }

    public function authenticate($credentials)
    {
        $adapter = $this->getAuthAdapter($credentials);
        $auth = $this->getAuth();
        $result = $auth->authenticate($adapter);

        if (!$result->isValid())
        {
            return false;
        }

        $user = $this->_userModel->getUserByName($credentials['username']);
        $auth->getStorage()->write($user);
        return true;
    }

    public function getAuth()
    {
        if (null === $this->_auth)
        {
            $this->_auth = Zend_Auth::getInstance();
        }
        return $this->_auth;
    }

    public function getIdentity()
    {
        $auth = $this->getAuth();
        if ($auth->hasIdentity())
        {
            return $auth->getIdentity();
        }
        return false;
    }

    public function clear()
    {
        $this->getAuth()->clearIdentity();
    }

    public function setAuthAdapter(Zend_Auth_Adapter_Interface $adapter)
    {
        $this->_authAdapter = $adapter;
    }

    public function getAuthAdapter($values)
    {
        if (null === $this->_authAdapter)
        {
            $authAdapter = new Zend_Auth_Adapter_DbTable(
                Zend_Db_Table_Abstract::getDefaultAdapter(),
                'authentication', //Table name
                'username',       //Identity column
                'password',       //Credential column
                'SHA1(CONCAT(?,salt))' //Treatment
            );
            $this->setAuthAdapter($authAdapter);
            $this->_authAdapter->setIdentity($values['username']);
            $this->_authAdapter->setCredential($values['password']);
            $this->_authAdapter->setCredentialTreatment('SHA1(CONCAT(?,salt))');
        }
        return $this->_authAdapter;
    }
}
