<?php

	require_once('doctrine/config.php');
	require_once('paths.config.php');

	class ContentsService
	{
		public function getFiles($start = 0, $offset = 20)
		{	
			$q = Doctrine_Query::create()
				->from('Contents c');
					
			$conts = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
			return $conts;
		}
		
		public function getFilesByTags($tags = NULL, $needle = NULL, $offset = 0, $limit = 20)
		{
			$q = Doctrine_Query::create()
				->from('Contents c')
				->leftJoin('c.TagsContents tc')
				->leftJoin('c.Tags t ON t.tag_id = tc.tag_id')
				->offset($offset)
				->limit($limit)
					;

			if($needle)
			{
				$q->where('c.name LIKE ?', '%' . $needle . '%');
				$q->where('c.filename LIKE ?', '%' . $needle . '%');
                $q->orWhere('t.name LIKE ?', '%' . $needle . '%');
			}


			if($tags)
			{
				foreach($tags as $tag)
				{
					$q->orWhere('t.name = ?', $tag->name);
				}
			}
			return $conts = $q->fetchArray();
		
		}

		public function getFilesWithFilters($tags, $needle, $offset, $limit)
		{
			$q = Doctrine_Query::create()
				->from('Contents c')
				->leftJoin('c.TagsContents tc')
				->leftJoin('c.Tags t ON t.tag_id = tc.tag_id')
				->offset($offset)
				->limit($limit)
					;

			if($needle)
			{
				$q->where('c.name LIKE ?', '%' . $needle . '%');
				$q->where('c.filename LIKE ?', '%' . $needle . '%');
                $q->orWhere('t.name LIKE ?', '%' . $needle . '%');
			}


			if($tags)
			{
				foreach($tags as $tag)
				{
					$q->orWhere('t.name = ?', $tag->name);
				}
			}
			return $conts = $q->fetchArray();

		}

		public function getFilesWithFiltersCount($tags, $needle)
		{
			$q = Doctrine_Query::create()
				->from('Contents c')
				->leftJoin('c.TagsContents tc')
				->leftJoin('c.Tags t ON t.tag_id = tc.tag_id')
					;

			if($needle)
			{
				$q->where('c.name LIKE ?', '%' . $needle . '%');
				$q->where('c.filename LIKE ?', '%' . $needle . '%');
                $q->orWhere('t.name LIKE ?', '%' . $needle . '%');
			}


			if($tags)
			{
				foreach($tags as $tag)
				{
					$q->orWhere('t.name = ?', $tag->name);
				}
			}
			return $q->count();
		}
		
		public function getFilesByTag($tagArg)
		{
			$q = Doctrine_Query::create()
				->from('Tags t')
				->leftJoin('t.TagsContents tc')
				->where('t.name = ?', $tagArg->name);
			$tag = $q->fetchOne();
			
			return $tag->Contents->toArray(false);
		}

		
		
		public function getTags($cont)
		{
		
			$q = Doctrine_Query::create()
				->from('Contents c')
				->where('c.content_id = ?', $cont->content_id);
			$content = $q->fetchOne();
			
			$retTags = array();
			$tags = $content->Tags;
			foreach ($tags as $tag)
			{
				$retTags[] = $tag->returnObject();
			}
			return $retTags;
			//print_r($retTags);
		}

                public function getThumb($cont)
                {
                    $q = Doctrine_Query::create()
                        ->from('Contents c')
                        ->where('c.content_id = ?', $cont->content_id);
                    $content = $q->fetchOne();
                    return $content->Thumbs->toArray();
                }

                public function contentPostUpload($user, $filename)
                {
                    // change spaces to underscore
                    $new_filename = str_replace(" ", "_", $filename);
                    $filename = $new_filename;


                    $type = '';
                    $total = 5; // at least five

                    $to_reduce = '';
                    // create the thumb
                    if (preg_match('/.flv|.mp4|.f4v/i', $filename))
                    {
                        $type = 'video';
                        $to_reduce = TMP_PATH .  "thumb_" . $filename . ".jpg";
                        // first take a frame
                        $cmd = FFMPEG_PATH . " -i " . CONTS_PATH . $filename . " -an -ss 00:00:05 -r 1 -vframes 1 -f mjpeg -y " . TMP_PATH .  "thumb_" . $filename . ".jpg";

                        exec($cmd, $ret);

                        copy(TMP_PATH . "thumb_" . $filename . ".jpg", THUMBS_PATH . "full_thumb_" . $filename . ".jpg");
     
                    }
                    else
                    {
                        $type = 'image';

                        // copy the image to thumbs dir as well
                        copy(CONTS_PATH . $filename, THUMBS_PATH . "full_thumb_" . $filename . ".jpg");

                        $to_reduce = CONTS_PATH . $filename;
                    }

                    $thumb;
                    if (!preg_match('/.swf$/i', $filename))
                    {
                        
                        // make the thumb
                        /* see if is jpg png or gif */
                        if(preg_match('/.jpg|.jpeg$/i', $to_reduce))
                        {
                            $src_img = imagecreatefromjpeg($to_reduce);
                        }
                        if(preg_match('/.png/i', $to_reduce))
                        {
                            $src_img = imagecreatefrompng($to_reduce);
                        }
                        if(preg_match('/.gif$/i', $to_reduce))
                        {
                            $src_img = imagecreatefromgif($to_reduce);
                        }
                        $thumb_img = imagecreatetruecolor(105, 78);
                        imagecopyresized($thumb_img, $src_img, 0, 0, 0, 0, 105, 78, imagesx($src_img), imagesy($src_img));
                        imagejpeg($thumb_img, THUMBS_PATH . "thumb_" . $filename . ".jpg");

                        // save the thumb in the database

                        $thumb = new Thumbs();
                        $thumb->path = "thumb_" . $filename . ".jpg";
                        $thumb->save();

                        // gather info for the content creation
                        
                        $cmd = FFMPEG_PATH . " -i " .  CONTS_PATH . $filename . " 2>&1";


                        $ret = '';
                        @exec($cmd, $ret);
                        $output = implode(' ', $ret);

                        if (preg_match('/Duration: ((\d+):(\d+):(\d+))/s', $output, $time)) {
                            $total = ($time[2] * 3600) + ($time[3] * 60) + $time[4];
                        }
                    }
                    else
                    {
                        $type = 'flash';
                    }


                    // now save the content
                    $cont = new Contents();

                    $cont->filename = $filename;
                    $cont->processed = false;
                    $cont->name = '';
                    $cont->size = filesize(CONTS_PATH . $filename);
                    $cont->type = $type;
                    $cont->duration = $total;
                    $cont->description = '';
                    $cont->user_id = $user->user_id;
                    $cont->uploaded = date('Y-m-d');
                    $cont->last_change = date('Y-m-d');
                    $cont->thumb_id = $thumb->thumb_id;
                    $cont->thumb_path = "thumb_" . $filename . ".jpg";
                    $cont->full_thumb_path = "full_thumb_" . $filename . ".jpg";
                    $cont->crc32 = dechex(crc32(file_get_contents(CONTS_PATH . $filename)));
                    //print_r($cont->toArray(true));

                    $cont->save();

                    $tag2 = Tags::insertTag('uncategorized', 'system');
                    $cont->linkTag($tag2);

                    $tag = Tags::insertTag($type, 'system');
                    $cont->linkTag($tag);

                    return true;

                }

                public function saveContent($cont)
                {
                    $q = Doctrine_Query::create()
                        ->from('Contents c')
                        ->where('c.content_id = ?', $cont->content_id);
                    $content = $q->fetchOne();
                    $content->duration = $cont->duration;
                    $content->last_change = date('Y-m-d');
                    $content->name = $cont->name;
                    $content->processed = true;
                    $content->save();

                    // remove spuriuos tag

                    $q = Doctrine_Query::create()
                        ->from('Tags t')
                        ->where('t.name = ?', 'uncategorized');
                    $uncategorized = $q->fetchOne();

                    $content->unlinkTag($uncategorized);

                    return true;
                }

                public function deleteContent($cont)
                {
                    $q = Doctrine_Query::create()
                        ->delete('Contents c')
                        ->where('c.content_id = ?', $cont->content_id);
                    $q->execute();
                }

                public function hasTag($cont, $tag)
                {
                    $q = Doctrine_Query::create()
			->from('Contents c')
			->leftJoin('c.TagsContents tc')
			->leftJoin('c.Tags t ON t.tag_id = tc.tag_id')
                        ->where('c.content_id = ?', $cont->content_id)
                        ->andWhere('t.tag_id = ?', $tag->tag_id);

                     $cont = $q->fetchOne();

                     if($cont)
                     {
                         return true;
                     }
                     else
                     {
                         return false;
                     }

                     return false;

                    

                }

                public function insertTag($cont, $tag)
                {
                    $q = Doctrine_Query::create()
                        ->from('Contents c')
                        ->where('c.content_id = ?', $cont->content_id);
                    $content = $q->fetchOne();

                    if($tag->tag_id)
                    {
                        $content->linkTag($tag);
                    }
                    else
                    {
                        $newTag = Tags::insertTag($tag->name, $tag->type);
                        $content->linkTag($newTag);
                    }
                    return true;
                }

                public function removeTag($cont, $tag)
                {
                    $q = Doctrine_Query::create()
                        ->from('Contents c')
                        ->where('c.content_id = ?', $cont->content_id);
                    $content = $q->fetchOne();
                    $content->unlinkTag($tag);
                    return true;
                }

                public function search($needle)
                {
                     $q = Doctrine_Query::create()
			->from('Contents c')
			->leftJoin('c.TagsContents tc')
			->leftJoin('c.Tags t ON t.tag_id = tc.tag_id')
                        ->where('c.name LIKE ?', '%' . $needle . '%')
						->where('c.filename LIKE ?', '%' . $needle . '%')
                        ->orWhere('t.name LIKE ?', '%' . $needle . '%');

                     return $q->fetchArray();


                }

	}
?>