<?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\Client;

use GuzzleHttp\Client as WebserviceClient;
use SimpleSAML\Module\lifestyle\Webservice\Api\Configuration\Client;
use SimpleSAML\Module\lifestyle\Webservice\Cyphering\Decoder;
use SimpleSAML\Module\lifestyle\Webservice\Cyphering\Encoder;
use SimpleSAML\Module\lifestyle\Webservice\Security\MessageDigestPasswordEncoder;

/**
 * Class Manager
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package SimpleSAML\Module\lifestyle\Webservice\Client
 */
class Manager
{
    /**
     * @var Client
     */
    private $configuration;

    /**
     * @var Encoder
     */
    private $cypheringEncoder;

    /**
     * @var Decoder
     */
    private $cypheringDecoder;

    /**
     * @var MessageDigestPasswordEncoder
     */
    private $passwordEncoder;

    /**
     * @var array
     */
    private $factory = array();

    /**
     * \SimpleSAML\Module\lifestyle\Webservice\Client\Manager constructor.
     * @param Client $configuration
     * @param Encoder $cypheringEncoder
     * @param Decoder $cypheringDecoder
     * @param MessageDigestPasswordEncoder $passwordEncoder
     */
    public function __construct(
        Client $configuration,
        Encoder $cypheringEncoder,
        Decoder $cypheringDecoder,
        MessageDigestPasswordEncoder $passwordEncoder
    ) {
        $this->configuration = $configuration;
        $this->cypheringEncoder = $cypheringEncoder;
        $this->cypheringDecoder = $cypheringDecoder;
        $this->passwordEncoder = $passwordEncoder;
    }

    /**
     * @return Request
     */
    public function request()
    {
        return isset($this->factory[__FUNCTION__]) ? $this->factory[__FUNCTION__] : ($this->factory[__FUNCTION__] = new Request($this->client(), $this->cypheringEncoder, $this->passwordEncoder, $this->configuration, $this->response()));
    }

    /**
     * @return Response
     */
    public function response()
    {
        return isset($this->factory[__FUNCTION__]) ? $this->factory[__FUNCTION__] : ($this->factory[__FUNCTION__] = new Response($this->cypheringDecoder, $this->passwordEncoder, $this->configuration));
    }

    /**
     * @return WebserviceClient
     */
    private function client()
    {
        return isset($this->factory[__FUNCTION__]) ? $this->factory[__FUNCTION__] : ($this->factory[__FUNCTION__] = new WebserviceClient(array('base_uri' => $this->configuration->getBaseUri())));
    }
}
