/*
 * mediareader.c: a class that reads media from database
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id$
 */
#include "mediareader.h"
#include "tools.h"

static char sqlMediaByGenre1[] = "SELECT vdr_Media.rowid, vdr_Media.title, "
	"vdr_Media.playtime, vdr_Media.fsk, vdr_Media.slot FROM vdr_Media WHERE "
	"vdr_Media.genre=%d ORDER BY vdr_Media.title";
 
static char sqlMediaByGenre2[] = "SELECT vdr_Media.rowid, vdr_Media.title, "
	"vdr_Media.playtime, vdr_Media.fsk, vdr_Media.slot FROM vdr_Media WHERE "
	"vdr_Media.genre=%d and vdr_Media.subgenre=%d ORDER BY vdr_Media.title";
 
static char sqlMediaByTitle[] = "SELECT vdr_Media.rowid, vdr_Media.title, "
	"vdr_Media.playtime, vdr_Media.fsk, vdr_Media.slot FROM vdr_Media WHERE "
	"vdr_Media.title like '%%%s%%' ORDER BY title";

static char sqlMediaByCast[] = "SELECT vdr_Media.rowid, vdr_Media.title, "
	"vdr_Media.playtime, vdr_Media.fsk, vdr_Media.slot FROM vdr_Media "
	"LEFT JOIN vdr_Cast ON vdr_Media.rowid=vdr_Cast.media "
	"LEFT JOIN vdr_Person ON vdr_Cast.person=vdr_Person.rowid "
	"WHERE vdr_Person.name like '%%%s%%' or vdr_Person.firstname like '%%%s%%'";
 

cMediaReader::cMediaReader(int genre)
{_
  asprintf(&sql, sqlMediaByGenre1, genre);
  Init();
}

cMediaReader::cMediaReader(int genre, int subgenre)
{_
  asprintf(&sql, sqlMediaByGenre2, genre, subgenre);
  Init();
}

cMediaReader::cMediaReader(char *what, char *pat)
{_
	if(!strcasecmp(what, "title")) 
		asprintf(&sql, sqlMediaByTitle, pat);
	else if(!strcasecmp(what, "cast")) 
		asprintf(&sql, sqlMediaByCast, pat, pat);
	else 
		SLWARN("unknown mode for media selection!");
	Init();
}

cMediaReader::~cMediaReader() 
{_
  SLDEBUG("# destructor of cMediaReader");
  free(sql);
}

cMenuMediaItem * cMediaReader::Read()
{_
  cMenuMediaItem * pGI = new cMenuMediaItem();
  cDataInfo	DatInf[] = {
	  { cDataInfo::INTEGER, (char *)&(pGI->id) - (char *)pGI },
	  { cDataInfo::TEXT,    (char *)&(pGI->title) - (char *)pGI },
	  { cDataInfo::INTEGER, (char *)&(pGI->playtime) - (char *)pGI },
	  { cDataInfo::INTEGER, (char *)&(pGI->fsk) - (char *)pGI },
	  { cDataInfo::TEXT,    (char *)&(pGI->slot) - (char *)pGI },
	  { cDataInfo::UNKNOWN, 0 }
     };
  return Super::Read(pGI, DatInf);	
}
