#include "mcdp.h"

/**
 * Copyright (C) 2001-2006 Tino Reichardt
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2, as
 * published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * 1) open the database
 * 2) search for 'tracks TT 150 10341 20449 45117 100104 150100 SSSS'
 * 3) fill cd->t[]
 *
 * tracks 6 150 10341 20449 45117 100104 150100 1609
 * playlist Originals 3 2 3 1
 * track 1111
 * track 2222
 * track 3333
 * track 4444
 * track 5555
 * track 6666
 */

static int db_wmdb_testdisc(const char *s);

void db_wmdb(void)
{
	stralloc sa;
	buffer b;
	int t, parse;


	if (buffer_mmapread(&b, mcdp_env_workmandb) == -1) {
		return;
	}

	parse=0;
	t=1;
	stralloc_init(&sa);
	while (buffer_getnewline_sa(&b, &sa) == 1) {

		/* skip empty lines */
		if (sa.len == 1) continue;

		/* skip comments */
		if (sa.s[0] == '#') continue;
		sa.s[sa.len] = 0; /* ensure termination */

		/* remove \r\n and \n */
		if (sa.s[sa.len-2] == '\r') sa.s[sa.len-2]=0;
		if (sa.s[sa.len-1] == '\n') sa.s[sa.len-1]=0;

		/* title of disc */
		if (!str_start(sa.s, "tracks")) {
			parse=db_wmdb_testdisc(sa.s+6);
		}

		if (parse) {
			if (!str_start(sa.s, "artist ")) {
				if (!stralloc_copys(&cd->t[0].name, sa.s+7)) die_nomem();
			}

			if (!str_start(sa.s, "cdname ")) {
				if (!stralloc_copys(&cd->t[0].extd, sa.s+7)) die_nomem();
			}

			if (!str_start(sa.s, "track ")) {
				if (t == MCDP_CDAUDIO_MAX) {
					die_msg(111, "MCDP_CDAUDIO_MAX reached!");
				}
				if (!stralloc_copys(&cd->t[t].name, sa.s+6)) die_nomem();
				t++;
			}
		}
	}

	cd->db=DB_CDDB;
	return;
}

static int db_wmdb_testdisc(const char *s)
{
	int track=1;
	int state=0;
	const char *x=s;
	unsigned int n;

	for (;;) {
		x+=scan_uint(x+1, &n)+1;

		switch (state) {
		case 0: /* count of tracks */
			if (n != cd->titles) return 0;
			state=1;
			break;
		case 1: /* cddb of track t */
			if (n != cd->t[track].cddb) return 0;
			if (track == cd->titles) state=2;
			track++;
			break;
		case 2:
			/* seconds of disc */
			if (n == cd->t[0].cddb/75) return 1;
			return 0;
		}
	}

	return 0;
}

