<?php

namespace ArcaSolutions\CoreBundle\Repository;

use ArcaSolutions\ClassifiedBundle\Entity\Classified;
use ArcaSolutions\CoreBundle\Interfaces\EntityModulesRowInterface;
use ArcaSolutions\EventBundle\Entity\Event;
use ArcaSolutions\ListingBundle\Entity\Listing;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr;

/**
 * BaseModule
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EntityModulesRowRepository extends EntityRepository implements EntityModulesRowInterface
{
    /**
     * @param Listing|Classified|Event $item
     * @param int                      $count This parameter is used to limit the quantity of images by level (The
     *                                        right way it would be a relationship between the item and level, but it's
     *                                        not possible yet)
     *
     * @return array
     * @throws \Exception
     */
    public function getGallery($item, $count)
    {
        return $this->getEntityManager()->createQueryBuilder()
            ->select('gimg')
            ->from('ImageBundle:Image', 'img')
            ->leftJoin('ImageBundle:GalleryImage', 'gimg', Expr\Join::WITH, 'gimg.imageId = img.id')
            ->leftJoin('ImageBundle:GalleryItem', 'gitem', Expr\Join::WITH, 'gitem.galleryId = gimg.galleryId')
            ->where('gitem.itemType = :module')
            ->andWhere('gitem.itemId = :id')
            ->orderBy('gimg.imageDefault', 'DESC')
            ->setMaxResults($count)
            ->setParameter('module', $this->getModuleName())
            ->setParameter('id', $item->getId())
            ->getQuery()
            ->getResult();
    }

    /**
     * Throws exception because each class must implements it
     */
    function getModuleName()
    {
        throw new \Exception('You must implements your own getModuleName');
    }
}
