<?php

namespace OfficeBrain\Bundle\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Translation\Translator;

use OfficeBrain\Bundle\BlogBundle\Entity\Tag;
use OfficeBrain\Bundle\BlogBundle\Form\TagType;

/**
 * Tag controller.
 *
 * @Route("admin/{_locale}/blog/tag")
 */
class TagController extends Controller
{

    /**
     * Lists all Tag entities.
     *
     * @Route("/", name="officebrain_blog_tag_index")
     * requirements={"records_per_page"="12|24|48|96|996","page"="\d+"},
     * defaults={"records_per_page"=12,"page"=1}),
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $this->request = $this->getRequest();    
        $em = $this->getDoctrine()->getManager();
        
        $page           = $this->request->get('page', '1');
        $option           = $this->request->query->get('option', NULL);
        $keywords           = $this->request->query->get('keywords', NULL);
        $recordsPerPage = $this->request->get('recordsPerPage', 10);
        $start_index    = (($page - 1) * $recordsPerPage - 1);
        $search = array('tagIsDeleted' => 0 );
        if($option!="" && $keywords!=""){
            if($option=="tagStatus"){
                $search[$option] = ($keywords=="Active") ? 1: 0 ;
            }else{
                $search[$option] = $keywords;
            }
        }
        //print_r($search);
        //die;
        $entities = $em->getRepository('OfficeBrainBlogBundle:Tag')->findBy($search, array('id' => 'DESC'));

        $paginator  = $this->get('knp_paginator');
        $data['pagination'] = $paginator->paginate($entities, $page, $recordsPerPage, array(), count($entities));
        if($page>1 && count($data['pagination']->getItems()) == 0) {
            
            return $this->redirect($this->generateUrl('officebrain_blog_tag_index', array('page'=> $page-1)));
            
        }
        
        return array(
            'data' => $data,
            'option'=>$option,
            'keywords'=>$keywords,
            'page'=>$page
        );
    }
    /**
     * Creates a new Tag entity.
     *
     * @Route("/new", name="officebrain_blog_tag_create")
     * @Template("OfficeBrainBlogBundle:Tag:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Tag();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

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

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

    /**
     * Creates a form to create a Tag entity.
     *
     * @param Tag $entity The entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Tag $entity)
    {
        $entity->setTagCreatedDate(new \DateTime());
        $entity->setTagUpdatedDate(new \DateTime());
        $form = $this->createForm(new TagType(), $entity, array(
            'action' => $this->generateUrl('officebrain_blog_tag_create'),
     
        ));

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

        return $form;
    }

    
    /**
     * Finds and displays a Tag entity.
     *
     * @Route("/{id}", name="officebrain_blog_tag_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Tag')->find($id);

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

        $deleteForm = $this->createDeleteForm($id);

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

    /**
     * Displays a form to edit an existing Tag entity.
     * @Route("/{id}", name="officebrain_blog_tag_edit")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Tag')->find($id);

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

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

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

    /**
    * Creates a form to edit a Tag entity.
    *
    * @param Tag $entity The entity
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Tag $entity)
    {
        $form = $this->createForm(new TagType(), $entity, array(
            'action' => $this->generateUrl('officebrain_blog_tag_update', array('id' => $entity->getId()))
        ));

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

        return $form;
    }
    /**
     * Edits an existing Tag entity.
     *
     * @Route("/edit/{id}", name="officebrain_blog_tag_update")
     * @Template("OfficeBrainBlogBundle:Tag:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('OfficeBrainBlogBundle:Tag')->find($id);

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

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

        if ($editForm->isValid()) {
            $em->flush();

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

        return array(
            'entity'      => $entity,
            'form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Tag entity.
     * @Route("/delete/{id}", name="officebrain_blog_tag_delete")
     */
    public function deleteAction(Request $request, $id)
    {
        
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('OfficeBrainBlogBundle:Tag')->find($id);

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

        // $em->remove($entity);
        // $em->flush();
        
        $entity->setTagIsDeleted(true);
        $em->persist($entity);
        $em->flush();
        

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

    /**
     * Creates a form to delete a Tag entity by id.
     * @param mixed $id The entity id
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('officebrain_blog_tag_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}
