/*
 * Copyright (C) 2009, 2010 by Nicole Faerber <nicole.faerber@dpin.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
 * 2 of the License, or (at your option) any later version.
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>

#include <sqlite3.h>

#include "rds.h"
#include "tmc.h"

sqlite3 *lcl_db;
int OutputFlags;

void test_rds_PI_cb(unsigned short PI, unsigned char ccode, unsigned char ptype, unsigned char pref, void *udata)
{
		printf("New PI=%d ccode=%X ptype=%X '%s' '%s' pref=%d\n", PI, ccode, ptype, ptype_stext[ptype], ptype_ltext[ptype], pref);
}

void test_rds_radiotext_cb(char *radio_text, void *udata)
{
	printf("New RT: '%s'\n", radio_text);
}

void test_rds_date_time_cb(struct tm *rds_time, void *udata)
{
	printf("RDS date/time: %s", asctime(rds_time));
}

void test_rds_sname_cb(char *sname, void *udata)
{
	printf("RDS sname='%s'\n", sname);
}

void test_tmc_msg_cb(char *msg, void *user_data)
{
	printf("\nTMC msg:\n%s", msg);
}

int open_radio(const char *name)
{
int fd;

	fd = open(name, O_RDONLY);
	if (fd > 0)
		return fd;
	else
		return 0;
}

int main(int argc, char **argv)
{
char rdevname[PATH_MAX] = "/dev/radio0";
unsigned short rdsgroup[4];
int rds_fd, i;

	rds_init();
	tmc_init();

	i = 1;
	while (i < argc) {
		if (strncmp("-all", argv[i], 4) == 0)
			OutputFlags |= ~0;
		if (strncmp("-di", argv[i], 3) == 0)
			OutputFlags |= RDS_OUTPUT_RDSINFO;
		if (strncmp("-rd", argv[i], 3) == 0)
			if (argc > i)
				strcpy(rdevname, argv[++i]);
		if (strncmp("-rt", argv[i], 3) == 0) {
			// OutputFlags |= RDS_OUTPUT_RADIO_TEXT;
			rds_set_radiotext_cb(test_rds_radiotext_cb, NULL);
		}
		if (strncmp("-ri", argv[i], 3) == 0) {
			// OutputFlags |= RDS_OUTPUT_STATION_ID;
			rds_set_sname_cb(test_rds_sname_cb, NULL);
		}
		if (strncmp("-tmc", argv[i], 4) == 0) {
			// OutputFlags |= RDS_OUTPUT_TMC;
			tmc_set_msg_cb(test_tmc_msg_cb, NULL);
		}
		if (strncmp("-eon", argv[i], 4) == 0)
			OutputFlags |= RDS_OUTPUT_EON;
		if (strncmp("-dt", argv[i], 3) == 0) {
			// OutputFlags |= RDS_OUTPUT_DATETIME;
			rds_set_date_time_cb(test_rds_date_time_cb, NULL);
		}
		if (strncmp("-ug", argv[i], 3) == 0)
			OutputFlags |= RDS_OUTPUT_UNKNGRP;
		if (strncmp("-pi", argv[i], 3) == 0) {
			// OutputFlags |= RDS_RECEIVE_INDICATOR;
			rds_set_PI_cb(test_rds_PI_cb, NULL);
		}
		i++;
	}

	if (!(rds_fd = open_radio(rdevname))) {
		perror("open radio:");
		return -1;
	}

	if (sqlite3_open("lcl.db", &lcl_db) != SQLITE_OK) {
		perror("open LCL database:");
		close(rds_fd);
		return -1;
	}

	while (1) {
		if (rds_receive_group(rds_fd, rdsgroup)) {
			/* group complete, start decode */
			rds_decode_group(rdsgroup);
		}
	}
	
return 0;
}

