/*
 *   libmetatag - A media file tag-reader library
 *   Copyright (C) 2003, 2004  Pipian
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <musicbrainz/mb_c.h>
#include "include/cdaudio.h"
#include "include/endian.h"
#include "../fmt.h"
#include "../config.h"
#include "include/unicode.h"
#include "include/tags.h"
#define BUFFER_SIZE 4096

#ifdef MAKE_BMP
#include <bmp/vfs.h>
#define fopen vfs_fopen
#define fclose vfs_fclose
#define fread vfs_fread
#define fseek vfs_fseek
#define ftell vfs_ftell
#define FILE VFSFile
#endif

int fetchCDAudio(metatag_t *meta, char *filename, char track)
{
	int retVal;
	musicbrainz_t mb;
	char *tmp;
	
	tmp = malloc(BUFFER_SIZE / 4 + 1);
	mb = mb_New();
	mb_SetDevice(mb, filename);
	pdebug("Submitting query to MusicBrainz...", META_DEBUG);
	retVal = mb_Query(mb, MBQ_GetCDInfo);
	if(retVal == 0)
	{
#ifdef META_DEBUG
		char error[129] = "";
		pdebug("ERROR: Query failed.", META_DEBUG);
		mb_GetQueryError(mb, error, 128);
		pdebug(fmt_vastr("REASON: %s", error), META_DEBUG);
#endif
		mb_Delete(mb);
		free(tmp);
		return 0;
	}
	pdebug("Selecting result...", META_DEBUG);
	retVal = mb_Select1(mb, MBS_SelectAlbum, 1);
	if(retVal == 0)
	{
		pdebug("ERROR: Album select failed.", META_DEBUG);
		mb_Delete(mb);
		free(tmp);
		return 0;
	}
	pdebug("Extracting MusicBrainz data from result...", META_DEBUG);
	memset(tmp, '\0', BUFFER_SIZE / 4 + 1);
	retVal = mb_GetResultData(mb, MBE_AlbumGetAlbumName, tmp, BUFFER_SIZE / 4);
	if(retVal == 0)
	{
		pdebug("ERROR: Album title not found.", META_DEBUG);
	}
	else
	{
		metatag_set_album(meta, tmp);
	}
	memset(tmp, '\0', BUFFER_SIZE / 4 + 1);
	retVal = mb_GetResultData1(mb, MBE_AlbumGetArtistName, tmp, BUFFER_SIZE / 4, track);
	if(retVal == 0)
	{
		pdebug("ERROR: Artist name not found.", META_DEBUG);
	}
	else
	{
		metatag_set_artist(meta, tmp);
	}
	memset(tmp, '\0', BUFFER_SIZE / 4 + 1);
	retVal = mb_GetResultData1(mb, MBE_AlbumGetTrackName, tmp, BUFFER_SIZE / 4, track);
	if(retVal == 0)
	{
		pdebug("ERROR: Track title not found.", META_DEBUG);
	}
	else
	{
		metatag_set_title(meta, tmp);
	}
	mb_Delete(mb);
	free(tmp);
	
	return 1;
}
