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

namespace Sso\RestBundle\Controller\UserWs\Version2;

use FOS\RestBundle\View\View;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use LifeStyle\Tools\RestAuthBundle\Security\Authentication\Token\UidentifyToken;
use FOS\RestBundle\Controller\Annotations\NamePrefix;
use FOS\RestBundle\Controller\FOSRestController;
use Sso\RestBundle\Worker\Worker as Worker;
use JMS\DiExtraBundle\Annotation as DI;
use FOS\RestBundle\Controller\Annotations\Get;
use Symfony\Component\HttpFoundation\Request;
use LifeStyle\Tools\CachingBundle\Annotations\LsCache;

/**
 * @NamePrefix("api_rest_")
 *
 * Class UserApplicationController
 * @package Sso\RestBundle\Controller\UserWs\Version2
 */
class UserApplicationController
{
    /**
     * @DI\Inject("rest_worker_manager")
     * @var Worker
     */
    protected $woM;

    /**
     *  This service fetches all applications for one user with all connected applications or only with the requested
     *  applications.
     *
     * #### Requests
     *
     *
     * #Request (header)
     *
     *      Key                 | Value               | Description
     *      ------------------- | ------------------- | --------------------------------------
     *      username            |  (string)           | your username
     *      useridentifier      |  (string)           | your useridentifier for given username
     *      servicetoken        |  (string)           | servicetoken from ws
     *
     * ## GET Request Parameters
     *      identifier = username, guid or email
     *      appName[]  = array of applications in response (if empty you will get all applications)
     *
     * Request example XML
     *
     *      GET /api/v2/sso-ws/userApplication/showDetails.xml?identifier=sb@life-style.de&appName[]=SsoAdmin
     *
     * Request example JSON
     *
     *      GET /api/v2/sso-ws/userApplication/showDetails.json?identifier=sb@life-style.de&appName[]=SsoAdmin
     *
     * ## Response success
     *
     * **Example (header)**
     *
     *          200 OK
     *
     * **Example JSON (body)**
     *
     *      {
     *        "code": 200,
     *        "status": "OK",
     *        "trackId": "4bda7d4f1d",
     *        "date": "2016-10-19T07:25:43+02:00",
     *        "scriptTimeSec": 0.8433,
     *        "userType": {
     *          "guid": "21ea3dc0505e41933246c23fae1a3dd9",
     *          "username": "c.szabo@life-style.de",
     *          "email": "c.szabo@life-style.de",
     *          "firstname": "Christian",
     *          "lastname": "Szabo",
     *          "active": 1,
     *          "deleted": 0,
     *          "authId": "",
     *          "mfaEnabled": 0
     *        },
     *        "applicationType": [
     *          {
     *            "name": "WebAdmin",
     *            "active": 1,
     *            "attributeType": [],
     *            "applicationRoleType": []
     *          },
     *          {
     *            "name": "Web30Pimcore",
     *            "active": 1,
     *            "attributeType": [
     *              {
     *                "type": "one",
     *                "name": "isAdmin",
     *                "value": "true"
     *              }
     *            ],
     *            "applicationRoleType": []
     *          }
     *        ]
     *      }
     *
     *
     * **Example XML (body)**
     *
     *
     *      <?xml version="1.0" encoding="UTF-8"?>
     *      <userApplicationShowDetails>
     *        <code>200</code>
     *        <status><![CDATA[OK]]></status>
     *        <trackId><![CDATA[f9db9cb3ab]]></trackId>
     *        <date><![CDATA[2016-10-19T07:26:38+02:00]]></date>
     *        <scriptTimeSec>0.7776</scriptTimeSec>
     *        <userType>
     *          <guid><![CDATA[21ea3dc0505e41933246c23fae1a3dd9]]></guid>
     *          <username><![CDATA[c.szabo@life-style.de]]></username>
     *          <email><![CDATA[c.szabo@life-style.de]]></email>
     *          <firstname><![CDATA[Christian]]></firstname>
     *          <lastname><![CDATA[Szabo]]></lastname>
     *          <active>1</active>
     *          <deleted>0</deleted>
     *          <authId><![CDATA[]]></authId>
     *          <mfaEnabled>0</mfaEnabled>
     *        </userType>
     *        <applicationType>
     *          <name><![CDATA[WebAdmin]]></name>
     *          <active>1</active>
     *        </applicationType>
     *        <applicationType>
     *          <name><![CDATA[Web30Pimcore]]></name>
     *          <active>1</active>
     *          <attributeType>
     *            <type><![CDATA[one]]></type>
     *            <name><![CDATA[isAdmin]]></name>
     *            <value><![CDATA[true]]></value>
     *          </attributeType>
     *        </applicationType>
     *      </userApplicationShowDetails>
     *
     * ## Response error
     *
     * **Example (header)**
     *
     *          400 Bad Request
     *
     * **Example JSON (body)**
     *
     *      {
     *        "code": 404,
     *        "status": "404",
     *        "message": "Not Found",
     *        "trackid": "ed4e0c252d",
     *        "scriptTimeSec": 0.766,
     *        "count": "1",
     *        "errors": [
     *          {
     *            "code": 404,
     *            "message": "ErrorCode: u001 ErrorRef:  ShortMessage: Invalid user",
     *            "exception": "external"
     *          }
     *        ]
     *      }
     *
     * **Example XML (body)**
     *
     *
     *      <?xml version="1.0" encoding="UTF-8"?>
     *      <userApplicationShowDetails>
     *        <code>404</code>
     *        <status><![CDATA[404]]></status>
     *        <message><![CDATA[Not Found]]></message>
     *        <trackid><![CDATA[53f8217df5]]></trackid>
     *        <scriptTimeSec>0.7085</scriptTimeSec>
     *        <count><![CDATA[1]]></count>
     *        <errors>
     *          <error>
     *            <code>404</code>
     *            <message><![CDATA[ErrorCode: u001 ErrorRef:  ShortMessage: Invalid user]]></message>
     *            <exception><![CDATA[external]]></exception>
     *          </error>
     *        </errors>
     *      </userApplicationShowDetails>
     *
     * @ApiDoc(
     *  resource="/api/{version}/sso-ws/userApplication",
     *  description="secured: get applications and details for user",
     *  statusCodes={
     *         200="Returned when successful",
     *         400="Returned when an error occured",
     *         500="Returned on internal server errors"
     *  },
     *  tags={
     *      "stable" = "#000"
     *  },
     * headers={
     *      {"name"="username", "description"="sso username"},
     *      {"name"="useridentifier", "description"="sso useridentifier"},
     *      {"name"="servicetoken", "description"="servicetoken"}
     *  },
     *  parameters = {
     *      { "name" = "identifier", "dataType" = "string", "required"=true},
     *      { "name" = "appName[]", "dataType" = "array", "required"=false}
     *  },
     *  views = { "sso-ws" }
     * )
     *
     * @Get("/v2/sso-ws/userApplication/showDetails", name="_sso-ws_v2", options={ "method_prefix" = true })
     * @Secure(roles="ROLE_API")
     * @LsCache(cacheTTL=300, keyHeader=true)
     * @param Request $request
     * @return View
     */
    public function userApplicationShowDetailsAction(Request $request)
    {
        return $this->woM->userWs()->version2()->userApplication()->showDetails()->init($request);
    }

    /**
     *
     * *This service returns user applications data. The service expects a JSON or XML in body and a header authentication.*
     *
     * #Request (header)
     *
     *      Key                 | Value               | Description
     *      ------------------- | ------------------- | --------------------------------------
     *      username            |  (string)           | your username
     *      useridentifier      |  (string)           | your useridentifier for given username
     *      servicetoken        |  (string)           | servicetoken from ws
     *
     * ##Request
     *
     * **Request example JSON**
     *
     *       /api/v2/userApplication/show.json?identifier=testUser&applicationActive=1
     *
     * **Request example XML**
     *
     *       /api/v2/userApplication/show.xml?identifier=testUser&applicationActive=1
     *
     * #Response success
     *
     * **Example JSON (body)**
     *
     *       {
     *           "code": 200,
     *           "status": "OK",
     *           "trackId": "ec9e298e96",
     *           "date": "2016-12-14T10:02:13+01:00",
     *           "scriptTimeSec": 5.649,
     *           "userApplications": {
     *               "userType": {
     *                   "code": 200,
     *                   "status": "OK",
     *                   "guid": "c1f7e15f81cd46d3b402ec0508781b32",
     *                   "username": "U0US130180",
     *                   "firstname": "firstName",
     *                   "lastname": "lastName",
     *                   "active": 0,
     *                   "deleted": 0,
     *                   "createdAt": "2016-09-06T14:06:45+02:00",
     *                   "updatedAt": "2016-09-06T14:06:45+02:00",
     *                   "authId": "",
     *                   "mfaEnabled": 0
     *               },
     *               "applicationType": [
     *                   {
     *                       "name": "Sso Employee",
     *                       "active": 1
     *                   },
     *                   {
     *                       "name": "Totara",
     *                       "active": 1
     *                   }
     *               ]
     *           }
     *       }
     *
     * **Example XML (body)**
     *
     *       <?xml version="1.0" encoding="UTF-8"?>
     *       <userApplication>
     *           <code>200</code>
     *           <status><![CDATA[OK]]></status>
     *           <trackId><![CDATA[3c44b35337]]></trackId>
     *           <date><![CDATA[2016-12-14T10:02:16+01:00]]></date>
     *           <scriptTimeSec>5.1415</scriptTimeSec>
     *           <userApplications>
     *               <userType>
     *                   <code>200</code>
     *                   <status><![CDATA[OK]]></status>
     *                   <guid><![CDATA[c1f7e15f81cd46d3b402ec0508781b32]]></guid>
     *                   <username><![CDATA[U0US130180]]></username>
     *                   <firstname><![CDATA[firstName]]></firstname>
     *                   <lastname><![CDATA[lastName]]></lastname>
     *                   <active>0</active>
     *                   <deleted>0</deleted>
     *                   <createdAt><![CDATA[2016-09-06T14:06:45+02:00]]></createdAt>
     *                   <updatedAt><![CDATA[2016-09-06T14:06:45+02:00]]></updatedAt>
     *                   <authId><![CDATA[]]></authId>
     *                   <mfaEnabled>0</mfaEnabled>
     *               </userType>
     *               <applicationType>
     *                   <name><![CDATA[Sso Employee]]></name>
     *                   <active>1</active>
     *               </applicationType>
     *               <applicationType>
     *                   <name><![CDATA[Totara]]></name>
     *                   <active>1</active>
     *               </applicationType>ionType>
     *           </userApplications>
     *       </userApplication>
     *
     * #Response error
     *
     * **Example JSON (body)**
     *
     *       {
     *           "code": 400,
     *           "status": "Bad Request",
     *           "date": "2016-12-14T09:59:13+01:00",
     *           "scriptTimeSec": 2.3368,
     *           "userApplications": {
     *               "errors": [
     *                   {
     *                       "code": 400,
     *                       "message": "ErrorCode: u001 ErrorRef: u2013 ShortMessage: Invalid user",
     *                       "exception": "external"
     *                   }
     *               ]
     *           }
     *       }
     *
     * **Example XML (body)**
     *
     *       <?xml version="1.0" encoding="UTF-8"?>
     *       <userApplication>
     *           <code>400</code>
     *           <status><![CDATA[Bad Request]]></status>
     *           <date><![CDATA[2016-12-14T10:01:13+01:00]]></date>
     *           <scriptTimeSec>5.2174</scriptTimeSec>
     *           <userApplications>
     *               <errors>
     *                   <error>
     *                       <code>400</code>
     *                       <message><![CDATA[ErrorCode: u001 ErrorRef: u2013 ShortMessage: Invalid user]]></message>
     *                       <exception><![CDATA[external]]></exception>
     *                   </error>
     *               </errors>
     *           </userApplications>
     *       </userApplication>
     *
     * ##Response error status 401, 416 or 500
     *
     * **Example JSON (body)**
     *
     *       {
     *       "code": 416,
     *       "status": "Not Found",
     *       "trackId": "2d008cc4c5",
     *       "scriptTimeSec": 1.521,
     *       "count": 1,
     *       "errors": [
     *          {
     *          "code": 416,
     *          "status": "Not Found",
     *          "message": "no valid json string",
     *          "type": "external",
     *          "exception": "InvalidRequest",
     *          "debug": "not set"
     *          }
     *         ]
     *       }
     *
     * **Example XML (body)**
     *
     *      <?xml version="1.0" encoding="UTF-8"?>
     *      <response>
     *          <code>416</code>
     *          <status><![CDATA[Not Found]]></status>
     *          <trackId><![CDATA[16fe523df4]]></trackId>
     *          <scriptTimeSec>2.4459</scriptTimeSec>
     *          <count>1</count>
     *          <errors>
     *              <error>
     *                <code>416</code>
     *                <status><![CDATA[Not Found]]></status>
     *                <message><![CDATA[expected '>']]></message>
     *                <type><![CDATA[external]]></type>
     *                <exception><![CDATA[InvalidRequest]]></exception>
     *                <debug><![CDATA[not set]]></debug>
     *              </error>
     *          </errors>
     *      </response>
     *
     * @ApiDoc(
     *  resource="/api/{version}/sso-ws/userApplication",
     *  description="secured: Gets user applications data from sso-ws",
     *  statusCodes={
     *         200="Returned when successful",
     *         204="Returned when no content was send",
     *         400="Returned when an error occurred",
     *         401="Unauthorized - Wrong credentials",
     *         403="Returned when the user is not authorized to do this request",
     *         416="Returned when the request is malformed",
     *         500="Returned on internal server errors"
     *  },
     *  headers={
     *      {
     *        "name"="username",
     *        "description"="sso username",
     *        "required"=true
     *       },
     *      {
     *        "name"="useridentifier",
     *        "description"="sso useridentifier",
     *        "required"=true
     *       },
     *      {
     *        "name"="servicetoken",
     *        "description"="servicetoken",
     *        "required"=true
     *       }
     *  },
     *  parameters={
     *      {"name"="identifier", "dataType"="string", "required"=true, "description"="User identifier"},
     *      {"name"="applicationActive", "dataType"="integer", "required"=false, "description"="Application active"}
     *  },
     *  tags={
     *      "stable" = "#000"
     *  },
     *  output="Sso\RestBundle\ModelRest\Response\UserWs\Version2\UserApplication\Show\Response",
     *  views = { "sso-ws" }
     * )
     *
     * @Get("/v2/sso-ws/userApplication/show", name="_sso-ws_v2", options={ "method_prefix" = true })
     * @Secure(roles="ROLE_API")
     * @LsCache(cacheTTL=300, keyHeader=true)
     * @param Request $request
     * @return View
     */
    public function userApplicationShowAction(Request $request)
    {
        return $this->woM->userWs()->version2()->userApplication()->show()->init($request);
    }
}
