<?php

namespace CacheBundle\Repository;

use CacheBundle\Entity\Category;
use CacheBundle\Entity\Feed\ClipFeed;
use Doctrine\ORM\EntityRepository;
use UserBundle\Entity\User;

/**
 * ClipFeedRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ClipFeedRepository extends EntityRepository
{

    /**
     * Get read later clip feed.
     *
     * @param integer $user Owner of read later feed.
     *
     * @return \CacheBundle\Entity\Feed\AbstractFeed|null
     */
    public function getReadLater($user)
    {
        return $this->createQueryBuilder('Feed')
            ->where('Feed.user = :user AND Feed.name = :name')
            ->setParameters([
                'user' => $user,
                'name' => ClipFeed::READ_LATER,
            ])
            ->getQuery()
            ->getOneOrNullResult();
    }

    /**
     * Create read later feed.
     *
     * @param integer $user Owner of read later feed.
     *
     * @return \CacheBundle\Entity\Feed\AbstractFeed
     */
    public function createReadLater($user)
    {
        $mainCategory = $this->_em->createQueryBuilder()
            ->select('partial Category.{id}')
            ->from(Category::class, 'Category')
            ->where('Category.user = :user AND Category.type = :type')
            ->setParameters([
                'user' => $user,
                'type' => Category::TYPE_MY_CONTENT,
            ])
            ->getQuery()
            ->getOneOrNullResult();

        $feed = ClipFeed::create()
            ->setName(ClipFeed::READ_LATER)
            ->setUser($this->_em->getReference(User::class, $user))
            ->setCategory($mainCategory);

        $this->_em->persist($feed);
        $this->_em->flush($feed);

        return $feed;
    }
}
