<?php

/**
 * @class WsLocationController
 * @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\BackendBundle\Controller;

use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Sso\Webservices\ObjectBundle\Entity;
use Sso\BackendBundle\Form;
use JMS\DiExtraBundle\Annotation\Inject;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Class WsObjectValuesController
 * @package Sso\BackendBundle\Controller
 */
class WsObjectValuesController extends WsAbstractController
{
    /**
     * @Inject("form.factory")
     * @var \Symfony\Component\Form\FormFactory
     */
    private $formFactory;

    /**
     * @Inject("lexik_form_filter.query_builder_updater")
     * @var \Lexik\Bundle\FormFilterBundle\Filter\FilterBuilderUpdater
     */
    private $lexikFilterUpdater;

    /**
     * @Inject("knp_paginator")
     * @var \Knp\Component\Pager\Paginator
     */
    private $knpPaginator;

    /**
     * @var \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    protected $file;

    /**
     * @Route("/", name="_admin_backend_webservice_object_values")
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $filterBuilder = $this->objectDbM()->respository()->objectAttributeValue()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\WsObjectValuesFilterType::class);

        $reset = false;
        if ($request->query->has('filter_action') && $request->query->get('filter_action') == 'reset') {
            $reset = true;
        }
        if ($request->query->has($form->getName()) && !$reset) {
            $form->submit($request->query->get($form->getName()));
            $this->lexikFilterUpdater->addFilterConditions($form, $filterBuilder);
        }
        $query = $filterBuilder->getQuery();
        $paginator = $this->knpPaginator;
        $pagination = $paginator->paginate($query, $request->query->get('page', 1), 10);

        return $this->render(
            '@SsoBackend/ws_object_values/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]
        );
    }

    /**
     * @Route("/select/object", name="_admin_backend_webservice_object_values_select_object")
     * @return Response
     */
    public function selectObjectAction()
    {
        $form = $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_webservice_object_values_select_group'))
            ->setMethod('POST')
            ->add('object', EntityType::class, [
                'class' => 'Sso\Webservices\ObjectBundle\Entity\Object',
                'choice_label' => 'name',
                'label' => "Object"
            ])
            ->add('submit', SubmitType::class, ['label' => 'Select Object'])
            ->getForm();

        return $this->render(
            '@SsoBackend/ws_object_values/select_object.html.twig',
            ['form' => $form->createView()]
        );
    }

    /**
     * @Route("/select/group", name="_admin_backend_webservice_object_values_select_group")
     * @param Request $request
     * @return Response
     */
    public function selectGroupAction(Request $request)
    {
        $inArray = $request->request->get('form');

        $valueId = $inArray['object'];
        $objectEntity = $this->objectDbM()->respository()->object()->find($valueId);

        $groupArray = [];
        $attributeGroups = $objectEntity->getType()->getAttributeGroups();
        foreach ($attributeGroups as $group) {
            $groupArray[$group->getId()] = $group->getName();
        }

        $form = $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_webservice_object_values_select_insert', []))
            ->setMethod('POST')
            ->add('object', HiddenType::class, [
                'data' => $valueId,
            ])
            ->add('attributeGroup', ChoiceType::class, [
                'label' => 'select a attribute group',
                'choices' => array_flip($groupArray)
            ])
            ->add('submit', SubmitType::class, ['label' => 'Select'])
            ->getForm();

        return $this->render(
            '@SsoBackend/ws_object_values/select_group.html.twig',
            ['form' => $form->createView(), 'objectEntity' => $objectEntity]
        );
    }

    /**
     * @Route("/select/insert", name="_admin_backend_webservice_object_values_select_insert")
     * @param Request $request
     * @return Response
     */
    public function selectInsertAction(Request $request)
    {
        $inArray = $request->request->get('form');

        $valueId = $inArray['object'];
        $objectEntity = $this->objectDbM()->respository()->object()->find($valueId);

        $attributeGroupId = $inArray['attributeGroup'];
        $attributeGroupEntity = $this->objectDbM()->respository()->attributeGroup()->find($attributeGroupId);

        $attributeArray = [];
        $attributes = $attributeGroupEntity->getAttributes();
        foreach ($attributes as $attribute) {
            $attributeArray[$attribute->getId()] = $attribute->getName();
        }

        $form = $this->createFormBuilder()
            ->setAction($this->generateUrl('_admin_backend_webservice_object_values_save', []))
            ->setMethod('POST')
            ->add('object', HiddenType::class, [
                'data' => $valueId,
            ])
            ->add('attributeGroup', HiddenType::class, [
                'data' => $attributeGroupId,
            ])
            ->add('attribute', ChoiceType::class, [
                'label' => 'Attribute',
                'choices' => array_flip($attributeArray)
            ])
            ->add('language', EntityType::class, [
                'class' => 'Sso\Webservices\ObjectBundle\Entity\Language',
                'choice_label' => 'name',
                'required' => true,
                'label' => 'Language'
            ])
            ->add('value')
            ->add('submit', SubmitType::class, ['label' => 'Select'])
            ->getForm();

        return $this->render(
            '@SsoBackend/ws_object_values/select_insert.html.twig',
            [
                'form' => $form->createView(),
                'objectEntity' => $objectEntity,
                'attributeGroupEntity' => $attributeGroupEntity
            ]
        );
    }

    /**
     * @Route("/save", name="_admin_backend_webservice_object_values_save")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function saveAction(Request $request)
    {
        $inArray = $request->request->get('form');
        $objectEntity = $this->objectDbM()->respository()->object()->find($inArray['object']);
        $attributeEntity = $this->objectDbM()->respository()->attribute()->find($inArray['attribute']);
        $languageEntity = $this->objectDbM()->respository()->language()->find($inArray['language']);

        $objectAttributeValueEntity = $this->objectDbM()->entity()->objectAttributeValue();
        $objectAttributeValueEntity->setAttribute($attributeEntity);
        $objectAttributeValueEntity->setLanguage($languageEntity);
        $objectAttributeValueEntity->setObject($objectEntity);
        $objectAttributeValueEntity->setValue($inArray['value']);

        try {
            $this->objectDbM()->data()->objectAttributeValue()->save($objectAttributeValueEntity);
            $this->get('session')->getFlashBag()->add('info', 'Value Saved Successfully');
        } catch (\Exception $exc) {
            $this->get('session')->getFlashBag()->add('info', $exc->getMessage());
        }

        return $this->redirect($this->generateUrl('_admin_backend_webservice_object_values'));
    }

    /**
     * @Route("/edit/{valueId}", name="_admin_backend_webservice_object_values_edit")
     * @param string $valueId
     * @throws NotFoundHttpException
     * @return Response
     */
    public function editAction($valueId)
    {
        $entity = $this->objectDbM()->respository()->objectAttributeValue()->find($valueId);
        if (!$entity) {
            throw $this->createNotFoundException('Type not found!');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($valueId);

        return $this->render(
            '@SsoBackend/ws_object_values/edit.html.twig',
            [
                'entity' => $entity,
                'edit_form' => $editForm->createView(),
                'delete_form' => $deleteForm->createView()
            ]
        );
    }

    /**
     * @param Entity\ObjectAttributeValue $entity
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createEditForm(Entity\ObjectAttributeValue $entity)
    {
        $form = $this->createForm(Form\WsObjectValuesType::class, $entity, [
            'action' => $this->generateUrl(
                '_admin_backend_webservice_object_values_update',
                ['valueId' => $entity->getId()]
            ),
            'method' => 'PUT',
        ]);

        $form->add('submit', SubmitType::class, ['label' => 'Update']);

        return $form;
    }

    /**
     * @Route("/update/{valueId}", name="_admin_backend_webservice_object_values_update")
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $valueId
     * @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function updateAction(Request $request, $valueId)
    {
        $entity = $this->objectDbM()->respository()->objectAttributeValue()->find($valueId);
        if (!$entity) {
            throw $this->createNotFoundException('Location not found!');
        }
        $deleteForm = $this->createDeleteForm($valueId);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $this->objectDbM()->data()->objectAttributeValue()->save($entity);
            $this->get('session')->getFlashBag()->add('info', 'Value Saved Sucess');

            return $this->redirect(
                $this->generateUrl('_admin_backend_webservice_object_values_edit', ['valueId' => $valueId])
            );
        }

        return $this->render(
            '@SsoBackend/ws_object_values/edit.html.twig',
            [
                'entity' => $entity,
                'edit_form' => $editForm->createView(),
                'delete_form' => $deleteForm->createView()
            ]
        );
    }

    /**
     * @Route("/delete/{valueId}", name="_admin_backend_webservice_object_values_delete")
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $valueId
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     * @throws NotFoundHttpException
     */
    public function deleteAction(Request $request, $valueId)
    {
        $form = $this->createDeleteForm($valueId);
        $form->handleRequest($request);
        $entity = $this->objectDbM()->respository()->objectAttributeValue()->find($valueId);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Value entity.');
        }

        $this->objectDbM()->data()->objectAttributeValue()->delete($entity);
        $this->get('session')->getFlashBag()->add('success', 'Types deleted.');

        return $this->redirect($this->generateUrl('_admin_backend_webservice_object_values'));
    }

    /**
     * @param $valueId
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createDeleteForm($valueId)
    {
        return $this->createFormBuilder()
            ->setAction(
                $this->generateUrl(
                    '_admin_backend_webservice_object_values_delete',
                    ['valueId' => $valueId]
                )
            )
            ->setMethod('DELETE')
            ->add('submit', SubmitType::class, ['label' => 'Delete'])
            ->getForm();
    }
}
