<?php

namespace Vipa\AnalyticsBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;

/**
 * ArticleStatisticRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ArticleStatisticRepository extends EntityRepository
{
    /**
     * Gets statistics of given articles on given dates
     *
     * @param array $articles
     * @param array $dates
     * @return ArrayCollection
     */
    public function findByArticles($articles, $dates = null)
    {
        $builder = $this->createQueryBuilder('stat');

        if ($dates !== null) {
            $builder
                ->andWhere('stat.date IN (:dates)')
                ->setParameter('dates', $dates);
        }

        $builder
            ->andWhere('stat.article IN (:articles)')
            ->orderBy('stat.date', 'DESC')
            ->setParameter('articles', $articles);

        return new ArrayCollection($builder->getQuery()->getResult());
    }

    /**
     * Gets statistics of most viewed amongst given articles
     *
     * @param array $articles
     * @param array $dates
     * @param int $limit
     * @return ArrayCollection
     */
    public function getMostViewed($articles, $dates = null, $limit = null)
    {
        $builder = $this->createQueryBuilder('stat');

        if ($dates !== null) {
            $builder
                ->andWhere('stat.date IN (:dates)')
                ->setParameter('dates', $dates);
        }

        $builder
            ->join('VipaJournalBundle:Article', 'article', 'WHERE', 'article = stat.article')
            ->addSelect('SUM(stat.view) as totalViews')
            ->andWhere('stat.article IN (:articles)')
            ->setParameter('articles', $articles)
            ->groupBy('stat.article, stat.id')
            ->orderBy('stat.view', 'DESC')
            ->setMaxResults($limit);

        return new ArrayCollection($builder->getQuery()->getResult());
    }
}
