<?php


namespace App\Model\Facades\Readers;


use App\Model\Entities\Components\Gallery\Gallery;
use App\Model\Entities\Image;
use App\Model\Services\GalleryService;
use Doctrine\Common\Collections\Criteria;

class GalleryReader extends BaseReader
{
    /** @var GalleryService */
    protected $galleryService;

    public function __construct(GalleryService $galleryService)
    {
        $this->galleryService = $galleryService;
    }

    public function findGalleryById(int $id)
    {
        $gallery = $this->galleryService->findGalleryById($id);
        $this->validateEntity($gallery);

        return $gallery;
    }

    public function findImages($gallery) : array
    {
        $galleryEntity = $this->validateGallery($gallery);
        $criteria = Criteria::create();
        $criteria->where(Criteria::expr()->eq('state', Image::PUBLISHED));

        return $galleryEntity->getImages()->matching($criteria);
    }

    public function validateGallery($gallery) : Gallery
    {
        if ($gallery instanceof Gallery) {
            return $gallery;
        }

        return $this->findGalleryById($gallery);
    }

}