<?php

namespace App\Repository;

use App\Entity\Commune;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\Query\Expr;
use App\Entity\Programm;
use App\Entity\Action;
use App\Entity\Activity;
use App\Entity\Notation;
use App\Entity\Target;
use App\Entity\Appreciation;
use App\Entity\Goal;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * @method Commune|null find($id, $lockMode = null, $lockVersion = null)
 * @method Commune|null findOneBy(array $criteria, array $orderBy = null)
 * @method Commune[]    findAll()
 * @method Commune[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class CommuneRepository extends ServiceEntityRepository
{
    private $session;
    
    public function __construct(SessionInterface $session, ManagerRegistry $registry)
    {
        parent::__construct($registry, Commune::class);
        $this->session = $session;
    }

    public function getSensitivity($year, Goal $goal, ?Target $target)
    {        
        $whereClause = $target ? 't.id = :target' : 'g.id = :goal';
        $paramClause = $target ? 'target' : 'goal';
        $paramObject = $target ? $target : $goal;

        $qb = $this->createQueryBuilder('m')
            ->select('m.code')
            ->addSelect('m.name')
            ->addSelect('SUM(n.sensitivity) AS sumSensitivity')
            ->addSelect('COUNT(n.activity) AS nbActivity')
            ->addSelect('SUM(CASE WHEN n.duplicated=false THEN y.amount ELSE 0 END) AS amount')

            ->innerJoin(Programm::class, 'p', Expr\Join::WITH, 'm.id = p.commune')
            ->innerJoin(Action::class, 'a', Expr\Join::WITH, 'p.id = a.programm')
            ->innerJoin(Activity::class, 'y', Expr\Join::WITH, 'a.id = y.action')
            ->innerJoin(Notation::class, 'n', Expr\Join::WITH, 'y.id = n.activity')
            ->innerJoin(Target::class, 't', Expr\Join::WITH, 't.id = n.target')
            ->innerJoin(Goal::class, 'g', Expr\Join::WITH, 'g.id = t.goal')

            ->andWhere('n.sensitivity != 0')
            ->andWhere('a.year = :year')
            ->andWhere($whereClause)
            ->andWhere($this->session->get('_commune') ? 'm.id= :commune' : '1 = :commune')

            ->setParameter('year', $year)
            ->setParameter($paramClause, $paramObject)
            ->setParameter('commune', $this->session->get('_commune') ? $this->session->get('_commune') : 1)
            ->groupBy('m.id') 
            ->orderBy('m.id', 'ASC')
            ;

        $rows = $qb->getQuery()->getResult();

        foreach ($rows as $key => $row) {
            $rows[$key]['sensitivity'] = $rows[$key]['nbActivity'] ? round($rows[$key]['sumSensitivity'] / $rows[$key]['nbActivity'], 2) : 0;
            $appreciation = $this->getEntityManager()
                ->getRepository(Appreciation::class)
                ->findOneByValue($rows[$key]['sensitivity']);
            $rows[$key]['appreciation'] = $appreciation->getName();
            $rows[$key]['flag'] = $appreciation->getFlag();
        }

        return array_reverse($rows);
    } 


    // /**
    //  * @return Commune[] Returns an array of Commune objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('c')
            ->andWhere('c.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('c.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Commune
    {
        return $this->createQueryBuilder('c')
            ->andWhere('c.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}
