<?php

/**
 * Steps Controller
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected 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  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Tools\UserIdentifierBundle\Api;

use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Stopwatch\Stopwatch;

/**
 * Steps Controller
 *
 * @copyright  Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */
class Controller
{

    /**
     * Api-Manager
     *
     * @var Manager
     */
    public $apiM;

    /**
     * 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)
    {
        $request = $this->apiM->modelFactory()->request();
        $request->credentials()->serviceCountry();
        $request->userIdentifier()->get()->key()->userType()
            ->setUsername($username)
            ->setPassword($password);

        // Set request options
        $options = array(
            'headers' => array(
                'SSO-API-VERSION' => '1',
                'SSO-API-CONTROLLER' => 'UserIdentifier',
                'SSO-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 false;
        }

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

        }
        return false;
    }

    /**
     *
     * @param string $username
     * @param string $userIdentifier
     * @return boolean
     */
    public function userIdentifierValidate($username, $userIdentifier)
    {
        //performance check
        if ($this->apiM->debugEnabled()) {
            $stopwatch = $this->apiM->stopWatch();
            $stopwatch->start('SSO-Debug-validateUserIentifier');
        }

        $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 false;
        }
        // Received response
        $response = $this->apiM->modelFactory()->response($webserviceResponse->getBody()->getContents());

        //performance check
        if ($this->apiM->debugEnabled()) {
            $stopwatch->stop('SSO-Debug-validateUserIentifier');
        }
        try {
            return 'Success' == $response->getStatus() && 'Success' == $response->getUserIdentifier()->validate()->getStatus();
        } catch (\Exception $ex) {

        }
        return false;
    }
}