<?php

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

namespace Sso\DemoBundle\Controller;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
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 AttributeController
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\DemoBundle\Controller
 */
class AttributeController extends BaseController
{
    /**
     * @Route("/", name="_sso_demo_attribute_show")
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function showAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Id', EntityType::class, [
                'class' => 'SsoWebservicesObjectBundle:Attribute',
                'choice_label' => 'Id',
                'required' => false,
            ])
            ->add('Offset', FormType\IntegerType::class, [
                'required' => false,
            ])
            ->add('Limit', FormType\IntegerType::class, [
                'required' => false,
            ])
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();

        return $this->_getResponseFromForm($form, $request, 'Attribute', 'Show');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeShow($params = [])
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <Attribute>
                            <Show>
                                <AttributeType>
                                    " . $this->_xmlBuildAttributeShowIdentifier($params) . "
                                </AttributeType>
                            </Show>
                        </Attribute>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function _xmlBuildAttributeShowIdentifier($params, $prefix = '')
    {
        $keys = ['Id', 'Offset', 'Limit'];
        return $this->xmlBuildIdentifier($keys, $params, $prefix);
    }

    /**
     * Build xml to identify type
     *
     * @param array $keys
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function xmlBuildIdentifier($keys, $params, $prefix = '')
    {
        $xml = [];
        foreach ($keys as $key) {
            if (in_array($key, ['Id', 'GroupId'])) {
                $idx = $prefix . $key;
                if (!empty($params[$idx])) {
                    $xml[] = '<' . $key . '>' . $params[$idx]->getId() . '</' . $key . '>';
                }
            } elseif ($key == 'DeleteReferences') {
                $idx = $prefix . $key;
                if (isset($params[$idx])) {
                    $xml[] = '<' . $key . '>' . ($params[$idx] ? 'true' : 'false') . '</' . $key . '>';
                }
            } elseif ($key == 'PossibleValues') {
                $idx = $prefix . $key;
                if (!empty($params[$idx])) {
                    $line = '<' . $key . '>';
                    foreach ($params[$idx] as $value) {
                        $line .= '<Value>' . $value . '</Value>';
                    }
                    $line .= '</' . $key . '>';
                    $xml[] = $line;
                }
            } else {
                $idx = $prefix . $key;
                if (!empty($params[$idx]) || $params[$idx] === 0) {
                    $xml[] = '<' . $key . '>' . $params[$idx] . '</' . $key . '>';
                }
            }
        }

        return implode("\n", $xml);
    }

    /**
     * @Route("/", name="_sso_demo_attribute_add")
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function addAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Name', TextType::class)
            ->add('Mandatory', CheckboxType::class, [
                'required' => false,
                'label' => 'Is mandatory',
                'label_attr' => [
                    'class' => 'checkbox-inline'
                ]
            ])
            ->add('PossibleValues', CollectionType::class, [
                'entry_type' => TextType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true,
                'required' => false
            ])
            ->add('DefaultValue', TextType::class, [
                'required' => false
            ])
            ->add('Translatable', CheckboxType::class, [
                'required' => false,
                'label' => 'Is translatable',
            ])
            ->add('GroupId', EntityType::class, [
                'class' => 'SsoWebservicesObjectBundle:AttributeGroup',
                'choice_label' => 'Id',
                'required' => false,
            ])
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();

        return $this->_getResponseFromForm($form, $request, 'Attribute', 'Add');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeAdd($params = [])
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <Attribute>
                            <Add>
                                <AttributeType>
                                    " . $this->_xmlBuildAttributeAddIdentifier($params) . "
                                </AttributeType>
                            </Add>
                        </Attribute>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function _xmlBuildAttributeAddIdentifier($params, $prefix = '')
    {
        $keys = ['Name', 'Mandatory', 'PossibleValues', 'DefaultValue', 'Translatable', 'GroupId'];
        return $this->xmlBuildIdentifier($keys, $params, $prefix);
    }

    /**
     * @Route("/", name="_sso_demo_attribute_update")
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function updateAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Id', EntityType::class, [
                'class' => 'SsoWebservicesObjectBundle:Attribute',
                'choice_label' => 'Id',
                'required' => true,
            ])
            ->add('Name', TextType::class)
            ->add('Mandatory', CheckboxType::class, [
                'required' => false,
                'label' => 'Is mandatory',
                'label_attr' => [
                    'class' => 'checkbox-inline'
                ]
            ])
            ->add('PossibleValues', CollectionType::class, [
                'entry_type' => TextType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true,
                'required' => false
            ])
            ->add('DefaultValue', TextType::class, [
                'required' => false
            ])
            ->add('Translatable', CheckboxType::class, [
                'required' => false,
                'label' => 'Is translatable',
            ])
            ->add('GroupId', EntityType::class, [
                'class' => 'SsoWebservicesObjectBundle:AttributeGroup',
                'choice_label' => 'Id',
                'required' => false,
            ])
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();

        return $this->_getResponseFromForm($form, $request, 'Attribute', 'Update');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeUpdate($params = [])
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <Attribute>
                            <Update>
                                <AttributeType>
                                    " . $this->xmlBuildAttributeUpdateIdentifier($params) . "
                                </AttributeType>
                            </Update>
                        </Attribute>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function xmlBuildAttributeUpdateIdentifier($params, $prefix = '')
    {
        $keys = ['Id', 'Name', 'Mandatory', 'PossibleValues', 'DefaultValue', 'Translatable', 'GroupId'];
        return $this->xmlBuildIdentifier($keys, $params, $prefix);
    }

    /**
     * @Route("/", name="_sso_demo_attribute_delete")
     * @Template()
     *
     * @param Request $request
     * @return array
     */
    public function deleteAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Id', EntityType::class, [
                'class' => 'SsoWebservicesObjectBundle:Attribute',
                'choice_label' => 'Id',
                'required' => true,
            ])
            ->add('DeleteReferences', CheckboxType::class, [
                'value' => 'true',
                'required' => false,
            ])
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();

        return $this->_getResponseFromForm($form, $request, 'Attribute', 'Delete');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeDelete($params = array())
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <Attribute>
                            <Delete>
                                <AttributeType>
                                    " . $this->xmlBuildAttributeDeleteIdentifier($params) . "
                                </AttributeType>
                            </Delete>
                        </Attribute>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function xmlBuildAttributeDeleteIdentifier($params, $prefix = '')
    {
        $keys = ['Id', 'DeleteReferences'];
        return $this->xmlBuildIdentifier($keys, $params, $prefix);
    }
}
