<?php

/**
 * Class AttributeGroupController
 *
 * 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  2017 Lifestyle Webconsulting GmbH
 * @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 Sso\DemoBundle\Form;
use Symfony\Component\Form\Extension\Core\Type as FormType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

/**
 * Class AttributeGroupController
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package    Sso\DemoBundle\Controller
 */
class AttributeGroupController extends BaseController
{
    /**
     * @Route("/", name="_sso_demo_attribute_group_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, array(
                'class' => 'SsoWebservicesObjectBundle:AttributeGroup',
                'choice_label' => 'Id',
                'required' => false,
            ))
            ->add('Offset', FormType\IntegerType::class, array(
                'required' => false,
            ))
            ->add('Limit', FormType\IntegerType::class, array(
                'required' => false,
            ))
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();
        return $this->_getResponseFromForm($form, $request, 'AttributeGroup', 'Show');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeGroupShow($params = array())
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <AttributeGroup>
                            <Show>
                                <AttributeGroupType>
                                    " . $this->_xmlBuildAttributeGroupShowIdentifier($params) . "
                                </AttributeGroupType>
                            </Show>
                        </AttributeGroup>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function _xmlBuildAttributeGroupShowIdentifier($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 = array();
        foreach ($keys as $key) {
            if (in_array($key, array('Id'))) {
                $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 . '>';
                }
            } 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_group_add")
     * @Template()
     */
    public function addAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Name', FormType\IntegerType::class)
            ->add('Id', FormType\IntegerType::class)
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();
        return $this->_getResponseFromForm($form, $request, 'AttributeGroup', 'Add');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeGroupAdd($params = array())
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <AttributeGroup>
                            <Add>
                                <AttributeGroupType>
                                    " . $this->_xmlBuildAttributeGroupAddIdentifier($params) . "
                                </AttributeGroupType>
                            </Add>
                        </AttributeGroup>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function _xmlBuildAttributeGroupAddIdentifier($params, $prefix = '')
    {
        $xml = array();
        $keys = ['Id', 'Name'];

        $typesNodeSet = false;

        foreach ($keys as $key) {
            $idx = $prefix . $key;
            if (!empty($params[$idx])) {
                if ($key == "Id") {
                    if (!$typesNodeSet) {
                        $xml[] = '<Types>';
                    }
                    $xml[] = '<Type>';
                    $xml[] = '<' . $key . '>' . $params[$idx] . '</' . $key . '>';
                    $xml[] = '</Type>';
                    if (!$typesNodeSet) {
                        $xml[] = '</Types>';
                    }
                    $typesNodeSet = true;
                } else {
                    $xml[] = '<' . $key . '>' . $params[$idx] . '</' . $key . '>';
                }
            }
        }
        return implode("\n", $xml);
    }

    /**
     * @Route("/", name="_sso_demo_attribute_group_update")
     * @Template()
     */
    public function updateAction(Request $request)
    {
        $form = $this->createFormBuilder($this->_getFormDefaults($request))
            ->add($this->buildFormCredentials())
            ->add('Id', EntityType::class, array(
                'class' => 'SsoWebservicesObjectBundle:AttributeGroup',
                'choice_label' => 'Id',
                'required' => true,
            ))
            ->add('Name', FormType\TextType::class)
            ->add('AddTypes', FormType\CollectionType::class, array(
                'entry_type' => Form\AttributeGroupUpdateType::class,
                'allow_add' => true,
                'allow_delete' => true,
            ))
            ->add('DeleteTypes', FormType\CollectionType::class, array(
                'entry_type' => Form\AttributeGroupUpdateType::class,
                'allow_add' => true,
                'allow_delete' => true,
            ))
            ->add('DeleteReferences', FormType\CheckboxType::class, array(
                'label' => 'DeleteReferences (ObjectValues)',
                'required' => true,
            ))
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();
        return $this->_getResponseFromForm($form, $request, 'AttributeGroup', 'Update');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeGroupUpdate($params = array())
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <AttributeGroup>
                            <Update>
                                <AttributeGroupType>
                                    " . $this->xmlBuildAttributeGroupUpdateIdentifier($params) . "
                                </AttributeGroupType>
                            </Update>
                        </AttributeGroup>
                    </SsoRequest>";
    }

    /**
     * Build xml to identify type
     *
     * @param array $params
     * @param string $prefix
     * @return string
     */
    protected function xmlBuildAttributeGroupUpdateIdentifier($params, $prefix = '')
    {
        $keys = ['Id', 'Name', 'AddTypes', 'DeleteTypes', 'DeleteReferences'];

        foreach ($keys as $key) {
            $idx = $prefix . $key;
            if (!empty($params[$idx])) {
                if (in_array($key, array('AddTypes', 'DeleteTypes'))) {
                    $xml[] = '<' . $key . '>';
                    foreach ($params[$idx] as $type) {
                        $xml[] = '<TypeId>' . $type->getId() . '</TypeId>';
                    }
                    $xml[] = '</' . $key . '>';
                } elseif ($key == 'Id') {
                    $xml[] = '<' . $key . '>' . $params[$idx]->getId() . '</' . $key . '>';
                } elseif ($key == 'DeleteReferences') {
                    $idx = $prefix . $key;
                    if (isset($params[$idx])) {
                        $xml[] = '<' . $key . '>' . ($params[$idx] ? 'true' : 'false') . '</' . $key . '>';
                    }
                } else {
                    $xml[] = '<' . $key . '>' . $params[$idx] . '</' . $key . '>';
                }
            }
        }

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

    /**
     * @Route("/", name="_sso_demo_attribute_group_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, array(
                'class' => 'SsoWebservicesObjectBundle:AttributeGroup',
                'choice_label' => 'Id',
                'required' => true,
            ))
            ->add('DeleteReferences', FormType\CheckboxType::class, array(
                'value' => 'true',
                'required' => false,
            ))
            ->add('build xml and make webservice request', FormType\SubmitType::class)
            ->getForm();
        return $this->_getResponseFromForm($form, $request, 'AttributeGroup', 'Delete');
    }

    /**
     * @var array $params
     * @return string
     */
    protected function _xmlAttributeGroupDelete($params = array())
    {
        return "<?xml version='1.0'?>
                    <SsoRequest>
                        " . $this->_xmlCredentials($params) . "
                        <AttributeGroup>
                            <Delete>
                                <AttributeGroupType>
                                    " . $this->xmlBuildAttributeGroupDeleteIdentifier($params) . "
                                </AttributeGroupType>
                            </Delete>
                        </AttributeGroup>
                    </SsoRequest>";
    }

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