<?php
/**
 * Copyright (c) 2016 Serhii Borodai <clarifying@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 */

namespace App\Authentication;


use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Authentication\AuthenticationServiceInterface;
use Zend\Authentication\Result;

/**
 * Class AggregateAuth
 * @package App\Authentication
 */
class AggregateAuth implements AuthenticationServiceInterface
{

    protected $userService;

    protected $supportService;

    protected $cookie = [];

    /**
     * AggregateAuth constructor.
     * @param UserService $userService
     * @param SupportService $supportService
     */
    public function __construct(UserService $userService, SupportService $supportService)
    {
        $this->userService = $userService;
        $this->supportService = $supportService;
    }


    /**
     * Authenticates and provides an authentication result
     * @return Result
     * @throws \Exception
     */
    public function authenticate()
    {
        $cookie = $this->cookie;

        if (isset($cookie[$this->userService->getCookieTokenName()]) && $token = $cookie[$this->userService->getCookieTokenName()]) {
            $this->userService->setToken($token);
            $result = $this->userService->authenticate();
//            if (!$result->isValid()) {
//                throw new \Exception(implode(PHP_EOL, $result->getMessages()), $result->getCode());
//            }
        } elseif (isset($cookie[$this->supportService->getCookieTokenName()]) && $token = $cookie[$this->supportService->getCookieTokenName()]) {
            $this->supportService->setToken($token);
            $result = $this->supportService->authenticate();
//            if (!$result->isValid()) {
//                throw new \Exception(implode(PHP_EOL, $result->getMessages()), $result->getCode());
//            }
        } else {
            $result = new Result(Result::FAILURE, null);
        }

        return $result;
    }

    /**
     * Set cookie params to get token info
     *
     * @param $cookie
     */
    public function setCookie($cookie)
    {
        $this->cookie = $cookie;
    }

    /**
     * Returns true if and only if an identity is available
     *
     * @return bool
     */
    public function hasIdentity()
    {
        return $this->userService->hasIdentity() || $this->supportService->hasIdentity();
    }

    /**
     * Returns the authenticated identity or null if no identity is available
     *
     * @return mixed|null
     */
    public function getIdentity()
    {
        $identity = null;

        if ($this->userService->hasIdentity()) {
            $identity = $this->userService->getIdentity();
        } elseif ($this->supportService->hasIdentity()) {
            $identity = $this->supportService->getIdentity();
        }
        return $identity;
    }

    /**
     * Clears the identity
     *
     * @return void
     */
    public function clearIdentity()
    {
        $this->userService->clearIdentity();
        $this->supportService->clearIdentity();
    }

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function clearCookie(ServerRequestInterface $request, ResponseInterface $response)
    {
        $response = $this->userService->clearCookie($request, $response);
        $response = $this->supportService->clearCookie($request, $response);
        return $response;
    }
}