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

namespace Sso\DemoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

/**
 * Class IndexController
 * @package Sso\DemoBundle\Controller
 */
class IndexController extends BaseController
{
    /**
     * @Route("/", name="_sso_demo_index")
     * @Template()
     */
    public function indexAction()
    {
        return [];
    }

    /**
     * @Route("/", name="_sso_demo_xml")
     * @Template()
     * @param Request $request
     * @return array
     * @throws \Sso\DemoBundle\Exception\DemoException
     */
    public function xmlAction(Request $request)
    {
        $formDefaults = [
            'Xml' => $this->xmlDefault($this->getFormDefaults()),
            'Controller' => 'ControllerName',
            'Action' => 'ActionName',
            'apiVersion' => 1
        ];
        $form = $this->createFormBuilder($formDefaults)
            ->add('Controller', 'text')
            ->add('Action', 'text')
            ->add('apiVersion',
                'choice', [
                    'choices' => [
                        1 => 'Version 1',
                        2 => 'Version 2',
                        3 => 'Version 3',
                        4 => 'Version 4',
                        5 => 'Version 5'
                    ],
                ])
            ->add('Xml',
                'textarea', [
                    'attr' => [
                        'rows' => 20,
                        'style' => 'font-family:monospace;',
                        'wrap' => 'off',
                    ],
                ])
            ->add('build xml and make webservice request', 'submit')
            ->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            $formData = $form->getData();
            list($xmlRequest, $xmlResponse) = $this->callWebservice(
                $formData['Xml'],
                $formData['Controller'],
                $formData['Action'],
                $formData['apiVersion']
            );
        } else {
            list($xmlRequest, $xmlResponse) = ['', ''];
        }

        return [
            'wsRequest' => $xmlRequest,
            'wsResponse' => $xmlResponse,
            'wsProfiler' => $this->urlProfiler,
            'form' => $form->createView(),
        ];
    }

    /**
     * @Route("/", name="_sso_demo_xml_utf8")
     * @Template()
     */
    public function xmlUtf8Action(Request $request)
    {
        $form = $this->createFormBuilder($this->getFormDefaults())
            ->add('ServiceToken', 'text')
            ->add('ServiceCountry', 'hidden')
            ->add('UserIdentifier', 'text')
            ->add('build xml and make webservice request', 'submit')
            ->getForm();

        return $this->getResponseFromForm($form, $request, 'UserApplicationAttribute', 'Set', 'xmlTestUtf8');
    }

    /**
     * @param array $params
     * @return string
     */
    protected function xmlDefault($params)
    {
        return $this->formatXml("<?xml version='1.0' encoding='utf-8'?>
                    <SsoRequest>
                        <Credentials>
                            <ServiceProvider>
                                <ServiceToken>" . $params['ServiceToken'] . "</ServiceToken>
                                <ServiceName>MyService</ServiceName>
                            </ServiceProvider>
                            <ServiceTrigger>
                                <UserIdentifier>" . $params['UserIdentifier'] . "</UserIdentifier>
                            </ServiceTrigger>
                            <ServiceCountry>
                                <Code>" . $params['ServiceCountry'] . "</Code>
                            </ServiceCountry>
                        </Credentials>
                        <ControllerName>
                            <ActionName>
                                <Type>
                                    <Field1>Field 1 Value</Field1>
                                    <Field2>Field 2 Value</Field2>
                                </Type>
                            </ActionName>
                        </ControllerName>
                    </SsoRequest>");
    }

    /**
     * @param array $formData
     * @param string $controller
     * @param string $action
     * @throws \Sso\DemoBundle\Exception\DemoException
     * @return string
     */
    protected function xmlTestUtf8($formData, $controller, $action)
    {
        $xml = '<?xml version="1.0" encoding="iso-8859-1"?>
                <SsoRequest>
                  ' . $this->xmlCredentials($formData) . '
                  <UserApplicationAttribute>
                    <Set>
                      <Key>
                        <UserType>
                          <Email>of@life-style.de</Email>
                        </UserType>
                        <ApplicationType>
                          <Name>TestApplication</Name>
                        </ApplicationType>
                      </Key>
                      <Value>
                        <AttributeType>
                          <Name>TestAttribute</Name>
                          <Type>one</Type>
                          <Value>Hello Wørld!</Value>
                        </AttributeType>
                      </Value>
                    </Set>
                  </UserApplicationAttribute>
                </SsoRequest>';

        return $this->callWebservice($xml, $controller, $action);
    }
}
