<?php

namespace Neag\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Neag\MainBundle\Entity\Menu;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;

class AdminMenuController extends ControllerAbstract
{
    /**
     * @Route("/admin/menu_item/edit/{id}")
     * @Template("NeagMainBundle:AdminMenu:edit.html.twig")
     */
    public function editAction($id = null)
    {
        $this->sessionStart();
        $this->clearCache();
        
        $request = $this->getRequest();             
        
        $DB = $this->get('database_connection');       
        
        $edit = false;
        $parent = null;
        if (!empty($id)) {
            $menu_item = $this->getDoctrine()
            ->getRepository('NeagMainBundle:Menu')
            ->find($id);
            if (!empty($menu_item)) {
                $edit = true; 
                $parent = $menu_item->getParent();
            }
        }        
        if ($request->query->has('parent_id')) {
            $parent = $this->getDoctrine()
            ->getRepository('NeagMainBundle:Menu')
            ->find($request->query->get('parent_id')); 
        }

        if (empty($menu_item)) {
            $menu_item = new Menu();
            $menu_item->setOrderId(0);
            $menu_item->setParent($parent);
            $menu_item->setTitle('');
            $menu_item->setActive(1);
            $menu_item->setDescription('');
        }       

        $form = $this->createFormBuilder($menu_item)
            ->add('title', 'text', Array('label' => 'Название'))
            ->add('link', 'text', Array('label' => 'Ссылка'))
            ->add('linkM', 'text', Array('label' => 'Ссылка в мобильной версии'))
            ->add('description', 'text', Array('label' => 'Описание', 'required' => false))
            ->add('imageSrc', 'text', Array('label' => 'Путь к изображению', 'required' => false))
            ->add('imageWidth', 'text', Array('label' => 'Ширина изображения', 'required' => false))
            ->add('imageHeight', 'text', Array('label' => 'Высота изображения', 'required' => false))
            //->add('linkWidcard', 'text', Array('label' => 'Маска ссылки'))
            ->add('active', 'choice', Array('choices' => array(1 => 'Да', 0 => 'Нет'), 'label' => 'Активный'))
            ->getForm();
            
        if ($request->isMethod('POST')) {
            $submitted_values = $_POST[$form->getName()];            
            $form->bind($request);
            if (empty($submitted_values['description'])) {
                $menu_item->setDescription('');
            }
            if ($form->isValid()) {
                // perform some action, such as saving the task to the database
                if (!$edit) {
                    $weight = $this->get('globals')->incrementValue($this->getDoctrine()->getRepository('NeagMainBundle:Menu'), 'orderId');
                    $menu_item->setOrderId($weight);
                }
                $em = $this->getDoctrine()->getManager();                
                $em->persist($menu_item);
                $em->flush();
                /*
                $parent_id = null;
                $parentCategory = $menu_item->getParent();
                if (!empty($parentCategory)) {
                    $parent_id = $parentCategory->getId();
                }
                */
                if ($edit) {
                    $this->message('Изменения внесены', 'ok');
                } else {
                    $this->message('Добавлен новый раздел меню', 'ok');
                }
                $params = Array();
                if (!empty($parent)) {
                    $params['parent_id'] = $parent->getId();
                }
                return $this->redirect($this->generateUrl('admin_menu_item_list', $params));
            }
        }
        
        $action_params = Array();
        if ($request->query->has('parent_id')) {
            $action_params['parent_id'] = $request->query->get('parent_id');
        }
        if (!empty($id)) {
            $action_params['id'] = $id;
        }
        $action_link = $this->generateUrl('admin_menu_item_edit', $action_params);    

        return array(
            'action' => $action_link,
            'form' => $form->createView(),
            'edit' => $edit,
        );
    }

    /**
     * @Route("admin/menu_item/{parent_id}")
     * @Template("NeagMainBundle:AdminMenu:list.html.twig")
     */
    public function listAction($parent_id = null)
    {       
        $this->sessionStart();
        $this->clearCache();
        
        $request = $this->getRequest();

                
        $del = $this->getRequest()->query->get('del'); 
        
        $DB = $this->get('database_connection'); 
        
        if (!empty($del)) {
            $menu_item = $this->getDoctrine()
            ->getRepository('NeagMainBundle:Menu')
            ->find($del);
            if (!empty($menu_item)) {
                $em = $this->getDoctrine()->getManager();                
                $em->remove($menu_item);
                $em->flush();
                $this->message('Раздел меню успешно удалён', 'ok');
            }
        }
        
        $repository = $this->getDoctrine()
        ->getRepository('NeagMainBundle:Menu'); 
        
        if (is_null($parent_id)) {
            $sql_part = 'c.parent IS NULL';
        } else {
            $sql_part = 'c.parent = '.(int)$parent_id;
        }
        //$this->trace($sql_part);
        
        $query = $repository->createQueryBuilder('c')
        ->where($sql_part)
        ->orderBy('c.orderId', 'ASC')
        ->getQuery();
        $rows = $query->getResult();
        $data = Array();
        foreach ($rows as $row) {
            $sub_count = 0;
            $repository2 = $this->getDoctrine()
            ->getRepository('NeagMainBundle:Menu');
            $sub_count = $repository2->createQueryBuilder('r')
            ->select(Array('COUNT(r.id)'))
            ->where('r.parent = :parent_id')
            ->setParameter('parent_id', $row->getId())
            ->getQuery()
            ->getSingleScalarResult();           
            //$sub_count = $rows2[0]['count'];
            $data[] = Array(
                'id' => $row->getId(),
                'title' => $row->getTitle(),                
                'description' => $row->getDescription(),
                'link' => $row->getLink(),
                'link_m' => $row->getLinkM(),
                //'link_wildcard' => $row->getLinkWidcard(),
                'place_up' => $row->getPlaceUp() ? 'да' : 'нет',
                'place_down' => $row->getPlaceDown() ? 'да' : 'нет',
                'active' => $row->getActive() ? 'да' : 'нет',
                'image_src' => $row->getImageSrc(),
                'image_width' => $row->getImageWidth(),
                'image_height' => $row->getImageHeight(),
                'sub_count' => $sub_count,
                'sub_link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => $row->getId())),
                'delete_link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => $parent_id, 'del' => $row->getId())),
                'edit_link' => $this->generateUrl('admin_menu_item_edit', array('id' => $row->getId())),
                'up_link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => $parent_id, 'up' => $row->getId())),
                'down_link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => $parent_id, 'down' => $row->getId())),
            );
        }
        $breadcrumbs = '';
        $breadcrumbs = $this->buildBreadcrumbs2($parent_id);
        //$this->trace($breadcrumbs);
        $params = Array();
        if (!empty($parent_id)) {
            $params['parent_id'] = $parent_id;
        }
        $add_link = $this->generateUrl('admin_menu_item_edit', $params);
        $rearrange_action = $this->generateUrl('admin_menu_item_rearrange');
        //$this->trace($parent_id);
        //$this->trace($add_link);
        return Array('data' => $data, 'breadcrumbs' => $breadcrumbs, 'add_link' => $add_link, 'rearrange_action' => $rearrange_action);
    }
    
    /**
     * Строит хлебные крошки
     * 
     * @access    public
     * @param     integer|null
     * @return    string
     */
    public function buildBreadcrumbs2($parent_id = null)
    {
        $data = $this->getBreadcrumbsData($parent_id);
        return parent::buildBreadcrumbs($data);
    }
    
    /**
     * Возвращает массив информации хлебных крошек для указанного родительского id
     * 
     * @access    public
     * @param     integer|null
     * @return    string
     */
    public function getBreadcrumbsData($id = null, $first_call = true)
    {
        $DB = $this->get('database_connection');        
        $data = Array();
        if ($id != null) {
            $category = $this->getDoctrine()
            ->getRepository('NeagMainBundle:Menu')
            ->find($id);
            if (!empty($category)) {
                $parent_id = null;
                $parent = $category->getParent();
                if (!empty($parent)) {
                    $parent_id = $parent->getId();
                }
                $data = $this->getBreadcrumbsData($parent_id, false);
                $data[] = Array(
                    'title' => $category->getTitle(),
                    'link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => $category->getId())),
                );
            }         
        }
        if ($id == null && !$first_call) {
            $params = Array(
                'title' => '<< Корень >>',
                'link' => $this->generateUrl('admin_menu_item_list', array('parent_id' => null)),
            );            
            array_unshift($data, $params);
        }  
        return $data;
    }
    
    /**
     * @Route("admin/menu_item_rearrange")
     */
    public function rearrangeAction()
    {
        $this->clearCache();
        $request = $this->getRequest();       
        $ids = $request->request->get('ids');
        $debug = '';
        if (!empty($ids) ? is_array($ids) : false) {
            $weight = 1;
            foreach ($ids as $id) {               
                if (!empty($debug)) {
                    $debug .= ', ';
                }
                $debug .= $id;                 
                $menu_item = $this->getDoctrine()
                ->getRepository('NeagMainBundle:Menu')
                ->find($id);                
                $debug .= '(cat:'.gettype($menu_item).')';                
                if (!empty($menu_item)) {
                    $menu_item->setOrderId($weight);                    
                    $em = $this->getDoctrine()->getManager();                                    
                    $em->persist($menu_item);
                    $em->flush();
                    $debug .= '(persists)';
                }                
                $weight++;
            }
        }
        $data = Array('status' => 'ok');
        //$data = Array('status' => 'ok', 'debug' => $debug);
        $response = new Response(json_encode($data));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    
    /**
     * Очищает кеш
     */
    public function clearCache()
    {
        $cm = $this->cacheManager();
        $cm->clear('menu');
        $cm->clear('menu_m');
    }  


}
