<?php

namespace Comitium5\DesignerBundle\Model\Traits;

use Comitium5\DesignerBundle\Helper\Utils;
use Comitium5\DesignerBundle\Model\Interfaces\UnknownInversedRelationsInterface;

/**
 * Trait UnknownInversedRelationsTrait
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Model\Traits
 */
trait UnknownInversedRelationsTrait
{
    /**
     * @param  array $ids
     * @param  int   $mode
     * @return array
     */
    public function getRelations(array $ids, $mode = 0)
    {
        if (!$this instanceof  UnknownInversedRelationsInterface) {
            return [];
        }

        $inversedRelations = $this->getUnknownInversedRelations();

        $om = $this->getObjectManager();

        $results = [];

        foreach ($inversedRelations as $className) {
            $query = $om
                ->getRepository($className)
                ->createQueryBuilder('e')
                ->select('COUNT(DISTINCT e.id)')
                ->join("e.{$this->getOrmRelationName()}", 't')
                ->andWhere("t.{$this->getOrmRelationQueryPropertyName()} IN (:entities)")
                ->setParameter('entities', $ids)
                ->getQuery();

            $nRelations = (int) $query->getSingleScalarResult();

            if ($nRelations > 0) {
                $results[] = [
                    'class' => $className,
                    'name'  => Utils::getEntityName($className),
                    'count' => $nRelations,
                ];
            }
        }

        return $results;
    }
}
