<?php

namespace App\Repository;

use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Tree\RepositoryInterface;
use Knp\Component\Pager\PaginatorInterface;
use Lc\SovBundle\Repository\AbstractRepositoryQuery;
use Lc\SovBundle\Repository\RepositoryQueryInterface;

class SearchRepositoryQuery extends AbstractRepositoryQuery implements RepositoryQueryInterface
{
    protected $isJoinCollectifData = false;
    protected $isJoinIndividualData = false;

    public function __construct($repository, PaginatorInterface $paginator)
    {
        parent::__construct($repository, 'r', $paginator);
    }

    public function filterIsValid()
    {
        $this->joinCollectifData();
        $this->joinIndividualData();

        return $this
            ->andWhere('colData.status = 1 OR indivData.status = 1');
    }

    public function filterByThematic(ArrayCollection $thematicArray): self
    {
        return $this
            ->andWhere('.thematic IN (:thematic)')
            ->setParameter(':thematic', $thematicArray);
    }

    public function filterByDescription(string $description): self
    {
        return $this
            ->andWhere('.description LIKE :description')
            ->setParameter(':description', '%' . $description . '%');
    }

    public function filterByTerritory(ArrayCollection $territoryArray): self
    {
        $this->joinCollectifData();
        $this->joinIndividualData();

        return $this
            ->andWhere('colData.territory IN (:territory) OR indivData.territory IN (:territory)')
            ->setParameter(':territory', $territoryArray);
    }

    public function joinCollectifData(): self
    {
        if (!$this->isJoinCollectifData) {
            $this->isJoinCollectifData = true;

            return $this
                ->leftJoin('.collectifData', 'colData');
        }
        return $this;
    }

    public function joinIndividualData(): self
    {
        if (!$this->isJoinIndividualData) {
            $this->isJoinIndividualData = true;

            return $this
                ->leftJoin('.individualData', 'indivData');
        }
        return $this;
    }
}
