<?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 Sso\WebserviceBundle\Services\UserApplication\ShowDetails\Response\Version3;

use Sso\WebserviceBundle\ErrorHandler\ErrorHandlerInterface;
use Sso\WebserviceBundle\Services\UserApplication\ShowDetails\ResponseBuilderInterface;
use Sso\WebserviceBundle\Services\ResponseBuilderInterface as GlobalResponseBuilderInterface;
use JMS\Serializer\SerializerInterface;
use Sso\WebserviceBundle\Services\UserApplication\ShowDetails\ResponseData\User as UserData;
/**
 * Class ResponseBuilder
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\WebserviceBundle\Services\UserApplication\ShowDetails\Response\Version3
 */
final class ResponseBuilder implements ResponseBuilderInterface, GlobalResponseBuilderInterface
{
    /**
     * @var SerializerInterface
     */
    private $serializer;

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

    /**
     * @var ErrorHandlerInterface
     */
    private $errorHandler;

    /**
     * @var UserData
     */
    private $responseData;

    /**
     * @var array
     */
    private $userTypeMapping = array(
        'getGuid' => 'guid',
        'getEmail' => 'email',
        'getUsername' => 'username',
        'getFirstname' => 'firstname',
        'getLastname' => 'lastname',
        'isActive' => 'active',
        'getAuthId' => 'authId',
        'getLdapSearchAttributes' => 'ldapSearchAttributes',
        'getLdapSearchValue' => 'ldapSearchValue',
        'isDeleted' => 'deleted',
        'getCreatedAt' => 'createdAt',
        'getUpdatedAt' => 'updatedAt',
        'getLastLoginAt' => 'lastLoginAt',
        'isMfaEnabled' => 'mfaEnabled',
        'getUserGroups' => 'userGroups',
    );

    /**
     * ResponseBuilder constructor.
     * @param SerializerInterface $serializer
     * @param Factory $factory
     * @param ErrorHandlerInterface $errorHandler
     */
    public function __construct(SerializerInterface $serializer, Factory $factory, ErrorHandlerInterface $errorHandler)
    {
        $this->serializer = $serializer;
        $this->factory = $factory;
        $this->errorHandler = $errorHandler;
    }

    /**
     * @param UserData $user
     */
    public function setResponse(UserData $user)
    {
        $this->responseData = $user;
    }

    /**
     * @return boolean
     */
    public function hasErrors()
    {
        return $this->errorHandler->hasErrors();
    }

    /**
     * @param string $format xml|json
     * @return string Response body
     */
    public function build($format)
    {
        $response = $this->errorHandler->hasErrors() ? $this->getErrorResponse() : $this->getSuccessResponse();
        return $this->serializer->serialize($response, $format);
    }

    /**
     * @return Response
     */
    private function getErrorResponse()
    {
        $response = $this->factory->response();
        $response->setErrors($this->errorHandler->getResponseObject());
        $response->setTrackid(null);
        $response->setDate(null);

        return $response;
    }

    /**
     * @return Response
     */
    private function getSuccessResponse()
    {

        $userType = $this->factory->userType();
        $userType->setFromArray($this->mapUserType($this->responseData));

        $show = $this->factory->showdetails();
        $show->setUserType($userType);
        $show->setStatus("Success");

        foreach ($this->responseData->getApplicationType() as $applicationType){
            //check read on application
            if(!in_array($applicationType->getName(), $this->factory->apiM()->userRolesApplicationRead())){
                continue;
            }
            $appType = $this->factory->applicationType();
            $appType->setActive($applicationType->getActive());
            $appType->setName($applicationType->getName());

            // add applicationRoleType
            foreach ($applicationType->getApplicationRoleType() as $userApplicationRole){

                $appRole = new ApplicationRoleType();
                $appRole->setName($userApplicationRole->getName());
                $appRole->setDescription($userApplicationRole->getDescription());
                $appRole->setActive($userApplicationRole->getActive());
                $appType->addApplicationRoleType($appRole);
            }

            // add attributeType
            foreach ($applicationType->getAttributeType() as $userApplicationAttribute){
                $appAtt = new AttributeType();
                $appAtt->setName($userApplicationAttribute->getName());
                $appAtt->setType($userApplicationAttribute->getType());
                $appAtt->setValue($userApplicationAttribute->getValue());
                $appType->addAttributeType($appAtt);
            }

            $show->addApplicationType($appType);
        }

        $user = $this->factory->userApplication();

        $user->addShow($show);

        $response = $this->factory->response();
        $response->setCode(200);
        $response->setScriptTimeSec($this->factory->scriptTimeSeconds());
        $response->setUserApplication($user);
        return $response;
    }

    /**
     * @param UserData $user
     * @return array
     */
    private function mapUserType(UserData $user)
    {
        $userType = array();
        foreach ($this->userTypeMapping as $getter => $attributeName) {
            $userType[$attributeName] = $user->$getter();
        }
        return $userType;
    }
}
