<?php

class EventUpdateService extends CComponent
{
  /**
   * 
   * @var Event
   */
  private $event;
  /**
   * 
   * @var EventBehavior[]
   */
  private $eventBehaviors;

  /**
   * 
   * @param Event $event
   * @param EventBehavior[] $eventBehaviors
   * @param array $params (usually $_POST)
   */
  public function __construct (Event $event, array $eventBehaviors = array(), array $params = array())
  {
    $this->event = $event;
    $this->eventBehaviors = $this->groupById($eventBehaviors);


    $this->saveBehaviors($params);
    $this->saveEvent($params);
  }

  /**
   * 
   * @return boolean
   */
  public function hasErrors()
  {
    if ($this->event->hasErrors())
      return true;

    foreach($this->eventBehaviors as $eventBehavior)
      if ($eventBehavior->hasErrors())
        return true;

    return false;
  }

  /**
   * 
   * @return Event
   */
  public function getEvent()
  {
    return $this->event;
  }

  /**
   * 
   * @return EventBehavior[]
   */
  public function getEventBehaviors()
  {
    return $this->eventBehaviors;
  }

  /**
   * 
   * @param array $params
   * @return boolean
   */
  private function saveEvent(array $params = array())
  {
    if (isset($params['Event']))
    {
      $this->event->attributes = $params['Event'];
      $this->event->updateStatus();
      $this->event->assignUser(Yii::app()->user);

      return $this->event->save();
    }
    return false;
  }

  /**
   * 
   * @param array $params
   */
  private function saveBehaviors(array $params = array())
  {
  	if(!array_key_exists('EventBehavior', $params))
  		return;
  		
    $eventBehaviors = $params['EventBehavior'];
    if (isset($eventBehaviors))
    {
      foreach($eventBehaviors as $attributes)
      {
        $eventBehavior = $this->eventBehaviors[$attributes['ID']];
        $eventBehavior->attributes=$attributes;
        $eventBehavior->save();
      }
    }
  }


  private function groupById($eventBehaviors)
  {
    return array_reduce($eventBehaviors, function(&$result, $b){ $result[$b->ID] = $b; return $result; }, array());
  }

}
