<?php

/**
 *
 * @class WsObjectController
 * @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\Component\HttpFoundation\Request;
use Sso\BackendBundle\Form;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Form\Extension\Core\Type as FormType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\DiExtraBundle\Annotation\Inject;
use Sso\BackendBundle\Entity;

/**
 * Class ImportController
 * @package Sso\BackendBundle\Controller
 */
class ImportController 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 \Sso\BackendBundle\Database\Manager
     */
    protected $dbBackendManager;

    /**
     * @Route("/", name="_admin_backend_import_index")
     * @param Request $request
     * @return Response
     */
    public function indexAction(Request $request)
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');
        $filterBuilder = $this->dbBackendManager->repository()->import()->createQueryBuilder('a');
        $form = $this->formFactory->create(Form\ImportFilterType::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);

        $form = $this->createFormBuilder()->add('attachment', FormType\FileType::class)
            ->add('objectType', FormType\ChoiceType::class, array(
                'choices' =>
                    $this->apiM()->getContainer()->get('api_backend_manager')->helper()->form()->getObjectTypesArray()
            ))
            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isValid()) {
                $this->file = $form['attachment']->getData();

                /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */
                $directory = $this->container->getParameter("kernel.cache_dir");
                $this->file->move($directory, $this->file->getClientOriginalName());
                // full file path with name
                $fullFilePath = $directory . "/" . $this->file->getClientOriginalName();
                $result = $this->container->get('api_backend_manager')->import()->worker()->objectExcelImport($fullFilePath,
                    $form->getData()['objectType']);
            }
        }
        return $this->render('@SsoBackend/import/index.html.twig',
            ['form' => $form->createView(), 'pagination' => $pagination]);
    }

    /**
     * @Route("/new", name="_admin_backend_import_new")
     * @return Response
     */
    public function newAction()
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');

        $entity = $this->dbBackendManager->entity()->import();
        $form = $this->createCreateForm($entity);

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

    /**
     * @param Entity\Import $entity
     * @return \Symfony\Component\Form\Form
     */
    private function createCreateForm(Entity\Import $entity)
    {
        $form = $this->createForm(Form\ImportType::class, $entity, array(
            'action' => $this->generateUrl('_admin_backend_import_create'),
            'method' => 'POST',
            'objects' => $this->apiM()->database()->webservice()->attribute()->getAllAttributesArray()
        ));

        $form->add('submit', FormType\SubmitType::class, array('label' => 'Create'));

        return $form;
    }

    /**
     * @Route("/create", name="_admin_backend_import_create")
     * @Template()
     */
    public function createAction(Request $request)
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');
        $entity = $this->dbBackendManager->entity()->import();

        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            try {
                $em = $this->dbBackendManager->getEntityManger();
                $em->persist($entity);
                $em->flush($entity);

            } catch (\Exception $exc) {
                $this->get('session')->getFlashBag()->add('error', $exc->getMessage());
                return $this->redirect($this->generateUrl('_admin_backend_import_index'));
            }

            $this->get('session')->getFlashBag()->add('success', 'Mapping created success');
            return $this->redirect($this->generateUrl('_admin_backend_import_index'));
        }

        return array('entity' => $entity, 'form' => $form->createView());
    }

    /**
     * @Route("/delete/{id}", name="_admin_backend_import_delete")
     * @Template()
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param string $tokenId
     * @return RedirectResponse
     * @throws Not
     */
    public function deleteAction(Request $request, $id)
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');
        $entity = $this->dbBackendManager->repository()->import()->find($id);

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

        $em = $this->dbBackendManager->getEntityManger();
        $em->remove($entity);
        $em->flush($entity);
        $this->get('session')->getFlashBag()->add('success', 'Mapping deleted.');


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


    /**
     * @Route("/edit/{id}", name="_admin_backend_import_edit")
     *
     * @param integer $id
     * @return Response
     * @throws NotFoundHttpException
     */
    public function editAction($id)
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');
        $entity = $this->dbBackendManager->repository()->import()->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Token not found!');
        }

        $editForm = $this->createEditForm($entity);
        return $this->render(
            '@SsoBackend/import/edit.html.twig',
            array(
                'entity' => $entity,
                'form' => $editForm->createView()
            )
        );
    }

    /**
     * @param Entity\Import $entity
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createEditForm(Entity\Import $entity)
    {
        $form = $this->createForm(new Form\ImportType($this->apiM()->database()->webservice()->attribute()->getAllAttributesArray()),
            $entity, array(
                'action' => $this->generateUrl('_admin_backend_import_update', array('id' => $entity->getId())),
                'method' => 'PUT',
            ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }

    /**
     * @param Request $request
     * @param string $id
     * @return RedirectResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAction(Request $request, $id)
    {
        $this->dbBackendManager = $this->container->get('db_backend_manager');
        $entity = $this->dbBackendManager->repository()->import()->find($id);
        if (!$entity) {
            throw $this->createNotFoundException('Mapping not found!');
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {

            $em = $this->dbBackendManager->getEntityManger();
            $em->persist($entity);
            $em->flush($entity);
            $this->get('session')->getFlashBag()->add('success', 'Mapping Saved Sucess');

        } else {
            $this->get('session')->getFlashBag()->add('success', 'Mapping Saved Error');
        }
        return $this->redirect($this->generateUrl('_admin_backend_import_index'));
    }
}
