<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_User
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * @category  Core
 * @package   Core_User
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */
class Core_User_AuthAdapter_Facebook implements Core_User_AuthAdapter_Interface
{
    /**
     *
     * @var Facebook
     */
    protected $_facebook;

    /**
     * Identity discovery service
     *
     * @var Core_User_IdentityDiscovery_Interface_Facebook
     */
    protected $_identityDiscovery;

    /**
     * Base doctrine query
     *
     * @var Doctrine_Query
     */
    protected $_query;

    /**
     *
     * @param Facebook $facebook
     */
    public function __construct(Facebook $facebook)
    {
        $this->_facebook = $facebook;
    }

    /**
     *
     * @return Core_User_IdentityDiscovery_Interface_Facebook
     */
    public function getIdentityDiscovery()
    {
        if (null === $this->_identityDiscovery) {
            throw new Exception('Error fetching identity discovery for auth adapter');
        }

        return $this->_identityDiscovery;
    }

    /**
     *
     * @param Core_User_IdentityDiscovery_Interface $identityDiscovery
     *
     * @return Core_User_AuthAdapter_Facebook
     */
    public function setIdentityDiscovery(Core_User_IdentityDiscovery_Interface $identityDiscovery)
    {
        $this->_identityDiscovery = $identityDiscovery;

        return $this;
    }

    /**
     * Get query
     *
     * @return Doctrine_Query
     */
    public function getQuery()
    {
        if (null === $this->_query) {
            $this->_query = $this->getIdentityDiscovery()
                ->createQuery('u')->select('u.*');
        }

        return $this->_query;
    }

    /**
     * Authenticate
     *
     * @return \Zend_Auth_Result
     */
    public function authenticate()
    {
        $facebookId = $this->_facebook->getUser();

        if (!$facebookId) {
            // No results
            return new Zend_Auth_Result(
                Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID,
                null,
                array('User not found')
            );
        }

        $entity = $this->getIdentityDiscovery()->findOneByFacebookId($facebookId);

        if (!$entity) {
            // No results
            return new Zend_Auth_Result(
                Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND,
                $this->_facebook->api('/me'),
                array('User not found')
            );
        }

        // All is good
        return new Zend_Auth_Result(
            Zend_Auth_Result::SUCCESS,
            $entity
        );
    }
}