<?php

namespace AppBundle\Helper;

use AppBundle\Entity\User;
use AppBundle\Enum\DemandePEEState;

class OperationHelper
{
    public static $user;
    
    /**
     * Set User
     * 
     * @param  $user
     */
    public static function setUser($user) {
        self::$user = $user;
    }
    
    /**
     * User MUST be setted first !
     * 
     * Reduce a list of operationPEE to the ones where the user has an application.
     * 
     * @param  array $operations MUST include the DemandePEE for a SPECIFIC USER too
     * @return array
     */
    public static function filterByUserApplication(array $operations): array
    {
        return array_filter($operations, function ($operation) {
            // return $operation['details']->getDemandepee()->count() > 0;

            $demandesPee = $operation['details']->getDemandepee();
            
            if ($demandesPee->count() > 0) {
                foreach ($demandesPee as $demandePee) {
                    if ( self::$user instanceOf User && $demandePee->getCuser()->getId() == self::$user->getId() && DemandePEEState::WITHDRAWAL !== $demandePee->getState() ) {
                        return true;
                    }
                }
            }
            
            return false;
        });
    }

    /**
     * User MUST be setted first !
     * Get the number of applications (DemandePEE) the user already has for the given operations.
     * Do not take into account if:
     * - the user does not have an application
     * - the user has an application, but it is a withdrawal
     * @param  array $operations MUST include the DemandePEE of a specific user
     * @return int
     */
    public static function getUserApplicationQty(array $operations): int
    {
        // return count(array_filter($operations, function ($operation) {
            // $demandesPee = $operation['details']->getDemandepee();

            // return 1 === $demandesPee->count() &&  DemandePEEState::WITHDRAWAL !== $demandesPee->first()->getState();
        // }));     
        
        return count(self::filterByUserApplication($operations));
    }
}
