<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace SimpleSAML\Module\lifestyle\Webservice\Handler\IdP\PostLoginSuccess;

use JMS\Serializer\Exception\Exception as SerializerException;
use JMS\Serializer\Serializer;
use SimpleSAML\Logger;
use SimpleSAML\Module\lifestyle\Webservice\Client\Request;
use SimpleSAML\Module\lifestyle\Webservice\Model\Request\IdP\Factory;
use SimpleSAML\Module\lifestyle\Webservice\Model\Response\IdP\PostLoginSuccess\Response;

/**
 * Class Handler
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package SimpleSAML\Module\lifestyle\Webservice\Handler\IdP\PostLoginSuccess
 */
class Handler
{
    const CLIENT_URL = '/api/v1/logins/successes';

    const CLIENT_METHOD = 'post';

    const CLIENT_FORMAT = 'json';

    /**
     * @var Request
     */
    private $client;

    /**
     * @var Factory
     */
    private $requestFactory;

    /**
     * @var Serializer
     */
    private $serializer;

    /**
     * \SimpleSAML\Module\lifestyle\Webservice\Handler\IdP\PostLogin\Handler constructor.
     * @param Request $client
     * @param Factory $requestFactory
     * @param Serializer $serializer
     */
    public function __construct(
        Request $client,
        Factory $requestFactory,
        Serializer $serializer
    ) {
        $this->client = $client;
        $this->requestFactory = $requestFactory;
        $this->serializer = $serializer;
    }

    /**
     * @param string $username
     * @return bool
     */
    public function handle($username)
    {
        $requestModel = $this->requestFactory->postLoginSuccess()
            ->setUserIdentifier($username);

        $response = $this->client->send(static::CLIENT_URL . '.' . static::CLIENT_FORMAT, static::CLIENT_METHOD, $this->serializer->serialize($requestModel, static::CLIENT_FORMAT));

        try {
            /** @var Response $responseModel */
            $responseModel = $this->serializer->deserialize($response, Response::class, static::CLIENT_FORMAT);
        } catch (SerializerException $exception) {
            Logger::warning('Error while reading response from user-webservice to login-request.');
            return false;
        }

        return true;
    }
}
