<?php

class CommonHelper
{
  public static function getTimeSchedulesOfGateForDay($gate, $day = null)
  {
    $day = DateHelper::ensureObjectEx($day);
    
    // fasce
    $idFascePermessi = query("SELECT distinct w.timeid as TimeID FROM whitelisttable w inner join abbonamentotable a on w.abbonamentoid=a.id where w.enabled=1 and w.to_be_confirmed<>1 and w.timeid in (select id from timetable) and date(a.datainizio) <= :dt and :dt <= date(a.datafine) AND (w.GateID=-1 OR w.GateID=:gt) AND w.enabled=1 AND w.to_be_confirmed<>1", array(':gt' => $gate, ':dt' => $day->toDateString()), false);
    $fascePermessi = array();
    foreach($idFascePermessi as $idFascia)
    {
      $fascia = TimeSchedule::model()->findByPk($idFascia->TimeID);
      if($fascia != null)
      {
        if($fascia->hasSlotsToday($day->toDateTime()))
          $fascePermessi[$idFascia->TimeID] = $fascia;
      }
    }
    
    return $fascePermessi;
  }
  
  /**
   * 
   * @param TimeSchedule[] $timeSchedules
   * @param mixed $now
   * @return TimeSchedule[]
   */
  public static function getWinningTimeSchedules($timeSchedules, $now)
  {
    $now = DateHelper::ensureObject($now);
    
    $winners = array();
    if($timeSchedules != null)
      foreach($timeSchedules as $timeSchedule)
      {
        $slot = $timeSchedule->getBestSlotToday($now);
        if($slot != null)
        {
          $winners[] = $slot->mySchedule;
        }
      }
    
    return $winners;
  }
  /**
   * 
   * @param TimeSchedule[] $timeSchedules
   * @param mixed $now
   * @return TimeSchedule
   */
  public static function getWinningTimeSchedule($timeSchedules, $now)
  {
    $now = DateHelper::ensureObject($now);
    
    $winners = array();
    foreach($timeSchedules as $timeSchedule)
    {
      $slot = $timeSchedule->getBestSlotToday($now);
      if($slot != null)
      {
        $winners[] = $slot;
      }
    }
    
    if(count($winners)>0)
    {
      $timeComparer = function($x,$y) { return $x->getPriority() > $y->getPriority() ? -1 : 1 ; };
      $winners = array_sort($winners, $timeComparer);
      return array_first($winners)->mySchedule;
    }
    
    return null;
  }
}
