<?php

/**
 * This class has been auto-generated by the Doctrine ORM Framework
 */
class ThdVideo extends BaseThdVideo
{
  public function addSegment($start, $end, $tags, $userUid) {
    $userObj = ThdUser::addUser($userUid);
    $segmentObj = new ThdSegment();
    $segmentObj->setStart($start);
    $segmentObj->setEnd($end);
    $segmentObj->setUserId($userObj->getId());
    $segmentObj->setVideoId($this->getId());
    $segmentObj->save();

    // Add tags to segment
    foreach ($tags as $tag) {
      $tagObj = ThdTag::addTag($tag);
      $segmentTagObj = new ThdSegmentTag();
      $segmentTagObj->setSegmentId($segmentObj->getId());
      $segmentTagObj->setTagId($tagObj->getId());
      $segmentTagObj->save();
    }
    
    $q = Doctrine_Query::create()
           ->from('ThdVideo v')
           ->innerJoin('v.ThdFilm f')
           ->where('v.id = ?', $this->id);

    $segment = $q->fetchOne();

    foreach ($tags as $tag_name) {
        $tags_array[] = array('segment_id'=>$this->ThdFilm->uniqueid,'name'=>$tag_name);
    }

    sfContext::getInstance()->getLogger()->info("insert segment " . print_r($tags_array,true));

    $dispatcher = sfContext::getInstance()->getEventDispatcher();
    $dispatcher->notify(new sfEvent($this, 'iri_sonyengine.tag_add', array('object'=>$tags_array, 'retrain'=>true)));

    $dispatcher->notify(new sfEvent($this, 'uvmc_solr.update_document', array('object' => $this->ThdFilm, 'commit' => true)));

    return $segmentObj;
  }

  public function getTags() {
    $tags = Array();

    // Create query
    $query = Doctrine_Query::create()
      ->select("ST.*, T.*")
      ->from('ThdSegmentTag ST')
      ->leftJoin('ST.ThdTag T')
      ->leftJoin('ST.ThdSegment S')
      ->leftJoin('S.ThdVideo V')
      ->where("V.id='{$this->getId()}'");

    foreach ($query->execute() as $item) {
      $tags[] = $item->getThdTag()->getTag();
    }

    return $tags;
  }

  public function getDistinctTags() {
    $tags = Array();

    foreach ($this->getTags() as $tag) {
      if (in_array($tag, $tags)) continue;
      $tags[] = $tag;
    }

    return $tags;
  }
}