<?php

class EventTagger {

    /**
     * 
     * @param Event[] $events
     * @throws CException
     * @return Event[]
     */
    static public function tag(array $events) {
        //$singleton = ExtCode::model()->singleton;

	      $dateTime = new DateTime ();


        foreach ($events as &$event)
        {
            if (!$event->tagged())
            {
                if ($event->isApproved())
                {
//          $singleton = ExtCode::model()->singleton;      	
//      	
//          $event = self::applyCodeToEvent($singleton->free_code, $event);
//
//          $singleton->free_code = self::generateNewCode($singleton->free_code);
//          
//          if(!$singleton->save())
//            throw new CException(Yii::t('app', 'Cannot update ExtCode singleton.'));

                    $event = self::applyCodeToEvent(ExtCode::generateNewCode(), $event, $dateTime);

                }
                else {
                    $event = self::applyCodeToEvent(ExtCode::NULL_EXT_CODE, $event, $dateTime);
                }
            
            }

      }
    return $events;
  }

  /**
   * 
   * @param number $oldCode
   * @return number
   */
  private static function generateNewCode($oldCode)
  {
    return $oldCode+1;
  }

  /**
   * 
   * @param number $newCode
   * @param Event $event
   * @throws CException
   * @return Event
   */
  private static function applyCodeToEvent($newCode, Event $event, $datetime)
  {
    if (!$event->tag($newCode, $datetime))
      throw new CException(Yii::t('app', 'Cannot set extcode {ext_code} for event # {event_id}.', array('{ext_code}' => $code, '{event_id}' => $event->ID)));
    return $event;
  }
}
