<?php

/**
 * video actions.
 *
 * @package    sf
 * @subpackage video
 * @author     Atma
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class videoActions extends sfActions
{
    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request)
    {
        $this->culture = $this->getUser()->getCulture();

        $this->videos = Doctrine_Query::create()
            ->select("v.*, t.*")
            ->from("Video v")
            ->innerJoin("v.Translation t")
            ->where("t.lang = ?", $this->getUser()->getCulture())
            ->andWhere("t.available = 1")
            ->fetchArray();

        $count_videos = count($this->videos);

        if ($request->getParameter('tag_id'))
        {
            $this->tag_id = $request->getParameter('tag_id');
        }else
        {
            $this->tag_id = 'all';
        }


        $tags = Doctrine_Query::create()
            ->select('t.*, tt.*, vt.*')
            ->from('Tag t')
            ->leftJoin('t.Translation tt WITH tt.lang = ?', $this->culture)
            ->leftJoin('t.VideoTags vt WITH vt.tag_id = t.id')
            ->fetchArray();

        $this->videos_tags = array();

        foreach ($tags as $tag)
        {
            if (count($tag['VideoTags']) > 0 )
            {
                $this->videos_tags[] = $tag;
            }
        }

        if ($request->getParameter('tag_id') && $request->getParameter('tag_id') != 'all' && $count_videos >= sfConfig::get('app_view_count_tag')) {
            unset($this->videos);

            $videos = Doctrine_Query::create()
                ->select('')
                ->from('Tag t')
                ->where('t.id = ?', $request->getParameter('tag_id'))
                ->leftJoin('t.VideoTags at WITH t.id = at.tag_id')
                ->leftJoin('at.Video a WITH at.video_id = a.id')
                ->innerJoin("a.Translation ta")
                ->andwhere("ta.lang = ?", $this->culture)
                ->andWhere("ta.available = 1")
                ->fetchArray();
            $this->videos = array();
            foreach ($videos[0]['VideoTags'] as $video) {
                $this->videos[] = $video['Video'];
            }
            $this->forward404Unless($this->videos);

        }

        if ($request->getParameter('tag_id') && $request->getParameter('ajax'))
        {
            sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
            echo include_partial('video/video', array('videos' => $this->videos, 'die' => true));
        }
    }
}
