<?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  2017 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Tools\UserIdentifierBundle\Api;

use GuzzleHttp\Exception\RequestException;

/**
 * Class Controller
 *
 * @copyright  2017 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\Tools\UserIdentifierBundle\Api
 */
class Controller implements ControllerInterface
{
    /**
     * Api-Manager
     * @var Manager
     */
    public $apiM;

    /**
     * As we do not get and validate in the same request, we can cache the results
     *
     * @var array
     */
    private $cache = [];

    /**
     * Constructor
     * @param Manager $apiM
     */
    public function __construct(Manager $apiM)
    {
        $this->apiM = $apiM;
    }

    /**
     * @param string $username
     * @param string $password
     * @return bool|string UserIdentifier on success, false otherwise
     */
    public function userIdentifierGet($username, $password)
    {
        $cacheId = 'userIdentifierGet' . hash('crc32', $username) . hash('crc32', $password);
        if (isset($this->cache[$cacheId])) {
            return $this->cache[$cacheId];
        }

        $request = $this->apiM->modelFactory()->request();
        $request->credentials()->serviceCountry();
        $request->userIdentifier()->get()->key()->userType()->setUsername($username)->setPassword($password);

        // Set request options
        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'UserIdentifier',
                'API-ACTION' => 'Get',
                'Content-Type' => 'text/xml; charset=UTF-8',
            ),
            'body' => $this->apiM->serializer()->serialize($request, 'xml'),
        );

        // Send request
        $client = $this->apiM->client();
        try {
            $webserviceResponse = $client->request('POST', null, $options);
        } catch (RequestException $exception) {

            // Received an error response
            $statusCode = $exception->hasResponse() ? $exception->getResponse()->getStatusCode() : 500;
            if ($statusCode < 500) {
                $this->apiM->logger()->warning(sprintf('Invalid credentials: %s', $exception->getMessage()));
            } else {
                $this->apiM->logger()->error(sprintf('Cannot get userIdentifier: %s', $exception->getMessage()));
            }

            return $this->cache[$cacheId] = false;
        }

        // Received response
        $response = $this->apiM->modelFactory()->response($webserviceResponse->getBody()->getContents());
        try {
            return $this->cache[$cacheId] = 'Success' == $response->getStatus() ? $response->getUserIdentifier()->get()->getUserType()->getUserIdentifier() : false;
        } catch (\Exception $exc) {
            unset($exc);
        }

        return $this->cache[$cacheId] = false;
    }

    /**
     * @param string $username
     * @param string $userIdentifier
     * @return boolean
     */
    public function userIdentifierValidate($username, $userIdentifier)
    {
        $cacheId = 'userIdentifierValidate' . hash('crc32', $username) . hash('crc32', $userIdentifier);
        if (isset($this->cache[$cacheId])) {
            return $this->cache[$cacheId];
        }

        $request = $this->apiM->modelFactory()->request();
        $request->credentials()->serviceCountry();
        $request->userIdentifier()->validate()->key()->userType()->setUsername($username)->setUserIdentifier($userIdentifier);

        // Set request options
        $options = array(
            'headers' => array(
                'API-VERSION' => '1',
                'API-CONTROLLER' => 'UserIdentifier',
                'API-ACTION' => 'Validate',
                'Content-Type' => 'text/xml; charset=UTF-8',
            ),
            'body' => $this->apiM->serializer()->serialize($request, 'xml'),
        );

        // Send request
        $client = $this->apiM->client();
        try {
            $webserviceResponse = $client->request('POST', null, $options);
        } catch (RequestException $exception) {

            // Received an error response
            $statusCode = $exception->hasResponse() ? $exception->getResponse()->getStatusCode() : 500;
            if ($statusCode < 500) {
                $this->apiM->logger()->warning(sprintf('Invalid userIdentifier: %s', $exception->getMessage()));
            } else {
                $this->apiM->logger()->error(sprintf('Cannot validate userIdentifier: %s', $exception->getMessage()));
            }

            return $this->cache[$cacheId] = false;
        }

        // Received response
        $response = $this->apiM->modelFactory()->response($webserviceResponse->getBody()->getContents());
        try {
            return $this->cache[$cacheId] = 'Success' == $response->getStatus() && 'Success' == $response->getUserIdentifier()->validate()->getStatus();
        } catch (\Exception $exc) {
            unset($exc);
        }

        return $this->cache[$cacheId] = false;
    }
}
