/***************************************************************************
 *            favorites.c
 *
 *  2011-05-28
 *  Copyright (C) 2011  Steffen Pohle
 *  steffen@gulpe.de
 ****************************************************************************/

/* 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * main.c 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, see <http://www.gnu.org/licenses/>.
 */

#include "favorites.h"
#include "memoryleak.h"
#include "system.h"

struct favorite *favorites = NULL;
int favorites_alloc = 0;
int favorites_cnt = 0;

char favfilename[LEN_FILENAME];

char *fav_getfilename () {
	snprintf (favfilename, LEN_FILENAME, "%s/favorites.txt", cfg.configpath);
	return favfilename;
};


void fav_load (char *filename) {
	struct favorite fav;
	FILE *f;
	char buf[1024];
	
	f =  fopen (filename, "r");
	if (f) {
		while (!feof (f)) {
			memset (buf, 0x0, 1024);
			fgets (buf, 1024, f);
			buf[1023] = 0;
			if (strchr (buf, ':') && strchr (buf, '#')) {
				sscanf (buf, "%f # %f",  &fav.pos.lon, &fav.pos.lat);
				strncpy (fav.name, strchr (buf, ':')+1, FAV_NAME_LEN);
				fav_add (-1, &fav);
			}
		}
		fclose (f);
	}
};


void fav_save (char *filename) {
	int i;
	FILE *f;
	
	f =  fopen (filename, "w");
	for (i = 0; i < favorites_cnt; i++) {
		fprintf (f, "%f # %f :%s\n", favorites[i].pos.lon, favorites[i].pos.lat, favorites[i].name);
		// d_printf ("fav_save wrote:'%f # %f :%s'",favorites[i].pos.lon, favorites[i].pos.lat, favorites[i].name);
	}
	fclose (f);
};


void fav_add (int nr, struct favorite *f) {
	/* add new or overwrite? */

	if (nr < 0 || nr >= favorites_cnt) {
		if (favorites_alloc <= favorites_cnt+1) {
			/* out of memory */
			struct favorite *fold = favorites;
			int fold_cnt = favorites_cnt;
			
			favorites_alloc += 32;
			favorites = (struct favorite *) ml_malloc (sizeof (struct favorite) * favorites_alloc);

			for (favorites_cnt = 0; favorites_cnt < fold_cnt; favorites_cnt++) {
				favorites[favorites_cnt] = fold[favorites_cnt];
			}

			ml_free (fold);
		}
		/* add new element and select for overwrite */
		nr = favorites_cnt;
		favorites_cnt++;
	}
	// d_printf ("fav_add nr:%d   %g , %g '%s'", nr, f->pos.lon, f->pos.lat, f->name);
	favorites[nr] = *f;
};


void fav_del (int nr) {
	int i;

	if (nr < 0 || nr >= favorites_cnt) return;

	for (i = nr; i < favorites_cnt-1; i++) {
		favorites[i] = favorites[i+1];
	}
	favorites_cnt--;
};


void fav_new () {
	favorites_cnt = 0;
};
