<?php

namespace VGM\WOBundle\Controller;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use VGM\WOBundle\Entity\NDepartment;
use VGM\WOBundle\Form\NDepartmentType;

/**
 * NDepartment controller.
 *
 */
class NDepartmentController extends Controller
{

    /**
     * Lists all NDepartment entities.
     *
     */
    public function indexAction($page)
    {
        $em = $this->getDoctrine()->getManager();

        $cant_departments = $em->getRepository('VGMWOBundle:NDepartment')->countDepartments();
        $departments_per_page = $this->container->getParameter('departments_per_page');
        $last_page = ceil($cant_departments / $departments_per_page);
        $previous_page = $page > 1 ? $page - 1 : 1;
        $next_page = $page < $last_page ? $page + 1 : $last_page;

        $offset = ($page - 1) > -1? ($page - 1) * $departments_per_page: null;
        $entities = $em->getRepository('VGMWOBundle:NDepartment')
            ->getDepartments($this->container->getParameter('departments_per_page'), $offset);

        return $this->render('VGMWOBundle:NDepartment:index.html.twig', array(
                'entities' => $entities,
                'last_page' => $last_page,
                'previous_page' => $previous_page,
                'current_page' => $page,
                'next_page' => $next_page,
                'cant_departments' => $cant_departments
            ));
    }
    /**
     * Creates a new NDepartment entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new NDepartment();
        $form = $this->createCreateForm($entity, new NDepartmentType());
        $form->handleRequest($request);

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

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

        return $this->render('VGMWOBundle:NDepartment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()));
    }

    /**
     * Creates a form to create a NDepartment entity.
     *
     * @param NDepartment $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(NDepartment $entity, NDepartmentType $type = null)
    {
        $form = null;

        if($type == null){
            $form = $this->createForm(new NDepartmentType(), $entity, array(
                'action' => $this->generateUrl('vgm_departments_create'),
                'method' => 'POST',
            ));

            $form->add('submit', 'submit', array('label' => 'Create'));
        }
        else{
            $form = $this->createForm($type, $entity, array(
                'action' => $this->generateUrl('vgm_departments_create'),
                'method' => 'POST',
            ));
        }

        return $form;
    }

    /**
     * Displays a form to create a new NDepartment entity.
     *
     */
    public function newAction()
    {
        $entity = new NDepartment();
        $form   = $this->createCreateForm($entity, new NDepartmentType());

        return $this->render('VGMWOBundle:NDepartment:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView()));
    }

    /**
     * Finds and displays a NDepartment entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:NDepartment')->find($id);
        $sups = $em->getRepository('VGMWOBundle:Worker')->getSupervisors();

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

        return $this->render('VGMWOBundle:NDepartment:show.html.twig', array(
            'dep' => $entity,
            'sups' => $sups
        ));
    }

    /**
     * Displays a form to edit an existing NDepartment entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:NDepartment')->find($id);

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

        $form   = $this->createEditForm($entity, new NDepartmentType());

        return $this->render('VGMWOBundle:NDepartment:edit.html.twig', array(
            'entity' => $entity,
            'edit_form'   => $form->createView(),
        ));
    }

    /**
    * Creates a form to edit a NDepartment entity.
    *
    * @param NDepartment $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(NDepartment $entity, NDepartmentType $type = null)
    {
        $form = null;

        if($type == null){
        $form = $this->createForm(new NDepartmentType(), $entity, array(
                'action' => $this->generateUrl('vgm_departments_update', array('id' => $entity->getId())),
                'method' => 'PUT',
            ));

            $form->add('submit', 'submit', array('label' => 'Update'));
        }
        else{
            $form = $this->createForm($type, $entity, array(
                'action' => $this->generateUrl('vgm_departments_update', array('id' => $entity->getId())),
                'method' => 'PUT',
            ));
        }

        return $form;
    }

    /**
     * Edits an existing NDepartment entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:NDepartment')->find($id);

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

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

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

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

        return $this->render('VGMWOBundle:NDepartment:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView()));
    }

    /**
     * Deletes a NDepartment entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('VGMWOBundle:NDepartment')->find($id);

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

            $em->remove($entity);
            $em->flush();
        }

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

    /**
     * Creates a form to delete a NDepartment 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('vgm_departments_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm();
    }

    /**
     * Ajax functions
     */
    //Proof ajax function
    public function getDepartmentsAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $departments = $em->getRepository('VGMWOBundle:NDepartment')->findBy(array(), array('name' => 'ASC'));

        $departments_list = [];

        foreach($departments as $dep){
            $departments_list[] = array("id" => $dep->getId(), "name" => $dep->__toString());
        }

        $response = array("code" => 100, "success" => true, "departments" => $departments_list, "message" => "Ok");

        return new Response(json_encode($response));
    }
    public function checkCreatingDepExistAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $name = $request->get('name');

        $exist = $em->getRepository('VGMWOBundle:NDepartment')->countDepartmentsByName($name) > 0 ? true : false;

        $response = array("code" => 100, "success" => true, "exist" => $exist);

        return new Response(json_encode($response));
    }
    public function checkUpdatingDepExistAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $name = $request->get('name');

        if($request->get('dep_id'))
            $dep_id = $request->get('dep_id');

        $exist = $em->getRepository('VGMWOBundle:NDepartment')->countDepartmentsByName($name) > 0 ?
            $em->getRepository('VGMWOBundle:NDepartment')->getDepartmentByName($name)->getId() == $dep_id ?
                false : true : false;

        $response = array("code" => 100, "success" => true, "exist" => $exist);

        return new Response(json_encode($response));
    }
    public function updateDepartmentAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $id = $request->get('id');
        $name = $request->get('name');
        $sup_id = $request->get('sup_id');
        $description = $request->get('description');

        $dep = $em->getRepository('VGMWOBundle:NDepartment')->find($id);
        $sup = $em->getRepository('VGMWOBundle:Worker')->find($sup_id);

        $dep->setName($name);
        $dep->setDescription($description);
        if($sup)
            $dep->setSupervisor($sup);

        $em->flush();

        $response = array("code" => 100, "success" => true, "message" => "Ok");

        return new Response(json_encode($response));
    }
}
