<?php

/**
 *
 * @class IndexController
 * @author sb
 *
 * 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
 * @version    $Id:$
 * @link       http://www.life-style.de
 *
 */

namespace Sso\DemoBundle\Controller;

use Sso\DemoBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type as FormType;

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

    /**
     * Check if database model contains any invalid elements
     */
    public function checkModelAction()
    {
        return $this->render('@SsoDemo/Index/check-model.html.twig', [
            'invalidObjects' => $this->apiM()->database()->webservice()->object()->findInvalidObjects()
        ]);
    }

    /**
     * @Route("/", name="_sso_demo_xml")
     * @Template()
     */
    public function xmlAction(Request $request)
    {
        $formDefaults = array(
            'Xml' => $this->_xmlDefault($this->_getFormDefaults()),
            'Controller' => 'ControllerName',
            'Action' => 'ActionName',
        );
        $form = $this->createFormBuilder($formDefaults)
            ->add('Controller', FormType\TextType::class)
            ->add('Action', FormType\TextType::class)
            ->add('Xml', FormType\TextareaType::class,
                array('attr' => array('rows' => 20, 'style' => 'font-family:monospace;', 'wrap' => 'off')))
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();

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

        return array(
            '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($this->buildFormCredentials())
            ->add('ServiceCountry', FormType\HiddenType::class)
            ->add('UserIdentifier', FormType\TextType::class)
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();
        return $this->_getResponseFromForm($form, $request, 'UserApplicationAttribute', 'Set', 'xmlTestUtf8');
    }

    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>");
    }

    /**
     * Test utf-encoded xml
     *
     * @param array $formData
     * @param string $controller
     * @param string $action
     */
    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);
    }
}
