<?php

class EventTagger
{
  /**
   * 
   * @param Event[] $events
   * @throws CException
   * @return Event[]
   */
  static public function tag(array $events)
  {
    $singleton = ExtCode::model()->singleton;
    
    foreach ($events as &$event)
    {
      if (!$event->tagged())
      {
      	if($event->isApproved())
      	{
          $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.'));
        }
        else
        {
          $event = self::applyCodeToEvent(ExtCode::NULL_EXT_CODE, $event);
        }
      }
    }
    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)
  {
    if (!$event->tag($newCode))
      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;
  }
}
