<?php

namespace Neag\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response; 
use Neag\MainBundle\Entity\Article;
use Neag\MainBundle\Entity\SimplePagePage;
use Neag\MainBundle\Entity\SimplePagePageRevision;

class ArchiveController extends ControllerAbstract
{
    /**
     * @Route("/archive")
     * @Template("NeagMainBundle:Archive:list.html.twig")
     */
    public function listAction()
    {
        $globals = $this->get('globals');
        $templating = $this->get('templating'); 
        $request = $this->get('request');
        
        $is_mobile = $globals->isMobile();
        
        $desktop_link = $this->generateURL('archive', array_merge(Array(), $this->get('request')->query->all()));
        $mobile_link = $this->generateURL('archive_m', array_merge(Array(), $this->get('request')->query->all()));
        $globals->setDesktopLink($desktop_link);
        $globals->setMobileLink($mobile_link);
        
        $take_from_cache = false;
        $currentPage = ($request->query->has('page'))? $request->query->get('page') : 1;
        if ($currentPage == 1) {
            if (!$is_mobile) {
                $cache_name = 'articles_1';
            } else {
                $cache_name = 'articles_1_m';
            }
            $cache = $this->cache($cache_name, Array('lifetime' => 3600*24*7));
            if ($cache->exists()) {
                $take_from_cache = true;
            } 
        }
        
        if (!$take_from_cache) {
        
            // Pager
            $pager = $this->get('punk_ave.pager_factory')->createPager("DoctrineORM");
            $request = $this->getRequest();
            $pager->bindRequest($request);
            $pager->setCurrentPage($currentPage);
            $pager->setMaxPerPage(50);
            $pager->setRoute($this->getRequest()->get('_route'), Array());
            // Анонсы
            $qb = $this->getDoctrine()->getManager()->createQueryBuilder()
            ->select(Array('a', 'p', 'pr'))
            //->select('p.id as id, p.path as path, p.articleAlias as articleAlias, pr.title as title, pr.annotation as annotation, p.time as time')
            ->from('NeagMainBundle:SimplePagePage', 'p')
            ->leftJoin('p.revisions', 'pr')
            ->leftJoin('p.articles', 'a')
            ->leftJoin('a.category', 'c');
            $qb->andWhere('p.active = :active')
            ->setParameter('active', true);
            $qb->andWhere('a.isShort = :isShort')
            ->setParameter('isShort', false);
            $qb->andWhere('a.showOnMain = :showOnMain')
            ->setParameter('showOnMain', true);
            $qb->andWhere('pr.current = :current')
            ->setParameter('current', true);
            $qb->orderBy('p.time', 'DESC');
            // prepare pager
            $globals->preparePager($pager, $qb, 'total_count/articles', Array('lifetime' => 3600*24*7));
            $pager->setQueryBuilder($qb);
            $rows = $pager->getResults();
            //$rows = $qb->getQuery()->getResult();
            $announces = Array();
            foreach ($rows as $row) {
                $revision = $globals->getPageCurrentRevision($row);
                $article = $globals->getPageArticle($row);
                if (!empty($revision) && !empty($article)) {
                    if (!$globals->hasArticleImagePreset($article, 'thumb')) {
                        $globals->createArticleImagePreset($article, 'thumb');
                    }
                    $announces[] = Array(
                        'title' => $revision->getTitle(),
                        'link' => $globals->buildPageLink($row),
                        'annotation' => $article->getAnnotation(),
                        'date' => $row->getTime()->format('d.m.Y'), 
                        'image' => $globals->getArticlePresetImageInfo($article, 'thumb'),
                    );
                }
            }
            $view = $templating->render(
                'NeagMainBundle:Archive:list.html.php',
                Array(
                    'announces' => $announces,
                    'pager' => $this->renderPager($pager),
                )
            );
            if ($currentPage == 1) {
                $cache->save($view);
            }    
        
        } else {
            $view = $cache->load();
        }           
        
        $params = Array(
            'is_mobile' => $is_mobile,
            'content' => $view,
        );
        return $params;
    }

}
