/*
 * This file is part of the ESO SINFONI Pipeline
 * Copyright (C) 2004-2009 European Southern Observatory
 *
 * 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.
 *
 * 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, 51 Franklin St, Fifth Floor, Boston, MA  02111-1307  USA
 */
/*
 * $Author: amodigli $
 * $Date: 2013-08-15 12:05:49 $
 * $Revision: 1.8 $
 */
#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <stdio.h>
//#include <unistd.h>
#include <string.h>

#include <cpl.h>
#include <cpl_test.h>
#include <sinfo_pro_save.h>
#include <sinfo_error.h>
#include <sinfo_msg.h>
#include <sinfo_utils_wrappers.h>
#include <sinfo_star_index.h>
#include <getopt.h>

const char* SINFO_STAR_BUG_REPORT = "amodigli@eso.org";
const double EPSILON = 1E-5;
const double DATA_1		= 209384.23;
const double DATA_2		= 378455.4398;
const char* COL_NAME_DATA = "DATA";
const char* FILE_NAME_FITS = "tmp_star_catalog.fits";
const char* FILE_NAME_FITS2 = "tmp_star_catalog2.fits";

struct _STAR_COORD_
{
	double RA;
	double DEC;
	double data_value;
	const char* STAR_NAME;
};

typedef struct _STAR_COORD_ STAR_COORD;

const STAR_COORD coords[] = {
		{300.982347, 18.34958, 958.229384, "STAR_UNO"},
		{30.234434, 180.23409, 2817.23847, "STAR_DUO"},
};

const STAR_COORD coords2[] = {
		{305.34892, 53.4319, 9545.234, "STAR_TRE"},
		{32.234434, 180.23409, 21348.78653, "STAR_QUA"},
		{2.234434, 45.2239, 8746.1236, "STAR_CIN"},
};

static void create_empty_test()
{
	star_index* pindex = star_index_create();
	cpl_test(pindex);
	star_index_delete(pindex);
        return;
}

static cpl_table* create_data_table(double data_value)
{
	cpl_table* retval = cpl_table_new(1);
	cpl_test(retval);
	cpl_test(CPL_ERROR_NONE == cpl_table_new_column(retval, COL_NAME_DATA, CPL_TYPE_DOUBLE));
	cpl_table_set_double(retval, COL_NAME_DATA, 0, data_value);
	return retval;
}

static void check_index(star_index* pindex, const STAR_COORD* pcoords, int size)
{
	int i = 0;
	for (i = 0; i < size; i++)
	{
		cpl_table* presult_data = star_index_get(pindex, pcoords[i].RA, pcoords[i].DEC, EPSILON, EPSILON, NULL);
		cpl_test(presult_data);
		int inull = 0;
		double result_data = cpl_table_get_double(presult_data, COL_NAME_DATA, 0, &inull);
		cpl_test_abs(result_data, pcoords[i].data_value, EPSILON);
		cpl_table_delete(presult_data);
	}
        return;
}

static void fill_index(star_index* pindex, const STAR_COORD* pcoords, int size)
{
	int i = 0;
	for (i = 0; i < size; i++ )
	{
		cpl_table* pdata = create_data_table(pcoords[i].data_value);
		star_index_add(pindex, pcoords[i].RA, pcoords[i].DEC, pcoords[i].STAR_NAME, pdata);
		cpl_table_delete(pdata);
	};
        return;
}

static void add_data_test()
{

	star_index* pindex = star_index_create();
	cpl_test(pindex);
      
	fill_index (pindex,coords, sizeof(coords) / sizeof(coords[0]));
	check_index(pindex,coords, sizeof(coords) / sizeof(coords[0]));
	star_index_save(pindex, FILE_NAME_FITS);
	star_index_delete(pindex);
        return;
}

static void load_file_test()
{
	star_index* pindex = star_index_load(FILE_NAME_FITS);
	check_index(pindex, coords, sizeof(coords) / sizeof(coords[0]));
	fill_index(pindex,coords2, sizeof(coords2) / sizeof(coords2[0]));
	check_index(pindex,coords2, sizeof(coords2) / sizeof(coords2[0]));
	check_index(pindex, coords, sizeof(coords) / sizeof(coords[0]));
	// remove from cache and main
	star_index_remove_by_name(pindex, coords[0].STAR_NAME);
	star_index_remove_by_name(pindex, coords2[0].STAR_NAME);
	check_index(pindex,coords2 + 1, sizeof(coords2) / sizeof(coords2[0]) - 1);
	check_index(pindex, coords + 1, sizeof(coords) / sizeof(coords[0]) - 1);
	// save, load and check again
	star_index_save(pindex, FILE_NAME_FITS2);
	star_index* pindex2 = star_index_load(FILE_NAME_FITS2);
	cpl_test(pindex2);
	check_index(pindex2,coords2 + 1, sizeof(coords2) / sizeof(coords2[0]) - 1);
	check_index(pindex2, coords + 1, sizeof(coords) / sizeof(coords[0]) - 1);
	star_index_delete(pindex);
	star_index_delete(pindex2);
        return;

}

static void create()
{
	star_index* pindex = star_index_load("star_index.fits");
	if (pindex)
	{
		cpl_table* pdata = cpl_table_load("gd71_stisnic_002.fits",1,0);
		if (pdata)
		{
			star_index_add(pindex, 88.115075, 15.88654, "gd71_stisnic", pdata);
			cpl_table_delete(pdata);
			star_index_save(pindex, "11star_index_v0_0_.fits");
		}
		star_index_delete(pindex);
	}
        return;
}

static cpl_error_code add_star(star_index* pindex, const char*name, double RA, double DEC, const char* fits_file_name)
{
	cpl_error_code err = CPL_ERROR_NONE;
	cpl_table* tbl = 0;
	tbl = cpl_table_load(fits_file_name, 1,0);
	if (tbl)
	{
		int pos = star_index_add(pindex, RA, DEC, name, tbl);
		if (pos == 0)
		{
			err = CPL_ERROR_ILLEGAL_INPUT;
		}
		cpl_table_delete(tbl);
	}
	else
	{
		fprintf(stderr,"cannot load table[%s]\n",fits_file_name);
		err = CPL_ERROR_FILE_IO;
	}
	return err;
}

static void list_catalog(star_index* pindex, FILE* file)
{
	star_index_dump(pindex, file);
}

static void remove_star(star_index* pindex, const char* star_name)
{
	star_index_remove_by_name(pindex, star_name);
}

static void save_catalog(star_index* pindex, const char* fits_file_name)
{
	const char* TMP_FILE_NAME = "star_index_tmp.fits";
	const char* EXT_BAK = ".bak";
	//1. save to the new file
	star_index_save(pindex, TMP_FILE_NAME);
	//2. rename old file to .bak
	char* bak_filename = cpl_malloc(strlen(fits_file_name) + strlen(EXT_BAK) + 1);
	strcpy(bak_filename, fits_file_name);
	strcpy(bak_filename + strlen(fits_file_name) , EXT_BAK);
	rename(fits_file_name, bak_filename); // don't care about result
	//3. rename new file
	rename(TMP_FILE_NAME, fits_file_name);
	cpl_free(bak_filename);
        return;
}

int main(int argc, char * const argv[])
{
	cpl_test_init(SINFO_STAR_BUG_REPORT, CPL_MSG_WARNING);
    int print_usage = 0;
	const char* index_file = 0 ;
	int opt = 0;

	if (argc < 2)
	{
		print_usage = 1;
	}
	else
	{
		index_file = argv[1];
	}
	if (index_file == 0)
	{
		print_usage = 1;
	}
	if(print_usage)
	{
		fprintf(stderr, "usage: %s catalog_name [-l | -a star_name RA DEC "
				"ref_fits_file.fits | -r star_name]\n"
				"-a option creates a new catalog, if catalog_name is not "
				"presented\n", argv[0]);
		return 0;
	}
	// open an index file
	star_index* pindex = star_index_load(index_file);

	// try to get a parameters, if nothing use -list as default
	opt = getopt(argc,argv,"lr:a:");
	if(pindex == NULL && opt=='a')
	{
		printf ("cannot open index file [%s], create new one\n", index_file);
		pindex = star_index_create();
	}
	if (pindex == NULL)
	{
		fprintf(stderr, "cannot open index file [%s]", index_file);
		return -1;
	}
	if (opt != -1)
	{
		switch (opt)
		{
		case 'l':
			printf("LIST\n");
			list_catalog(pindex, stdout);
			break;
		case 'r':
		{
			const char* star_name = optarg;
			printf("REMOVE [%s]\n", star_name);
			remove_star(pindex, star_name);
			save_catalog(pindex,index_file);
			//star_index_save(pindex,index_file);
		}
			break;
		case 'a':
		{
			const char* star_name = optarg;
			double RA = atof(argv[optind]);
			double DEC = atof(argv[optind+1]);;
			const char* fits_file = argv[optind+2];
			printf("ADD [%s] coord[%f:%f] file:%s\n", star_name, RA, DEC, fits_file);
			cpl_error_code err = add_star(pindex, star_name, RA, DEC, fits_file);
			if (err == CPL_ERROR_NONE)
			{
				printf ("save to [%s]\n", index_file);
				save_catalog(pindex,index_file);
			}
			else
			{
				printf("error during add\n");
			}
		}
			break;
		default:
			fprintf(stderr, " Urecognized option, usage: %s catalog_name [-l | -a star_name RA DEC ref_fits_file.fits | -r star_name]\n", argv[0]);
			break;

		}
	}


	create_empty_test();
	add_data_test();
	load_file_test();
	create();
	cpl_test_end(0);
	return 0;
}
