/* saveLocale.c
 * Called by gddcalc when the user presses the "clear" button on
 * the locale display. Clears the entry boxes of the locale display
 * and deletes any file named "locale.txt" that exists.
 */

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include "gddcalc.h"
#include <stdbool.h>

void saveLocale() {

	char bfr[32];
	FILE *fp;

/* If Locale.txt exists, remove it. Otherwise, open a new file with this name */

	fp = fopen("locale.txt", "w");
	if (fp != NULL) unlink("locale.txt");
	if ((fp = fopen("locale.txt", "w")) == NULL) {
		printf("\nCould not open %s for writing\n", "locale.txt");
		return;
	}
	
/* Read the persistant descriptors the user has typed into the display */

	const gchar *text1 = gtk_entry_get_text(GTK_ENTRY(locale_entry_lat));
	active_latitude = atof(text1);
	const gchar *text2 = gtk_entry_get_text(GTK_ENTRY(locale_entry_lon));
	active_longitude = atof(text2);
	const gchar *text3 = gtk_entry_get_text(GTK_ENTRY(locale_entry_elev));
	active_elev = atof(text3);
	const gchar *text4 = gtk_entry_get_text(GTK_ENTRY(locale_entry_aspect));
	active_aspect = atof(text4);
	const gchar *text5 = gtk_entry_get_text(GTK_ENTRY(locale_entry_tilt));
	active_tilt = atof(text5);

/* Check these values for appropriateness. In the special case that all the
 * descriptors are blank, we just remove locale.txt and disable all but the
 * close window button.
 */
	if (strlen(text1) == 0 && strlen(text2) == 0 && strlen(text3) == 0
			&& strlen(text4) == 0 && strlen(text5) == 0) {
		unlink("locale.txt");
		gtk_widget_set_sensitive(GTK_WIDGET(locale_clear), FALSE);
		gtk_widget_set_sensitive(GTK_WIDGET(locale_save), FALSE);
		gtk_widget_set_sensitive(GTK_WIDGET(locale_close), TRUE);
		return;
	}

/* The descriptors are not all blank, so check them for appropriateness.
 * If there are problems with them, disable the close window button so that
 * the user will be unable to create a bad locale.txt file.
 */
//	if (!LocaleOK(3)) {
//		gtk_widget_set_sensitive(GTK_WIDGET(locale_clear), TRUE);
//		gtk_widget_set_sensitive(GTK_WIDGET(locale_save), TRUE);
//		gtk_widget_set_sensitive(GTK_WIDGET(locale_close), FALSE);
//		return;
//	}

/* The descriptors are OK, so write them to the file and close the window.
 * We leave only the close window button enabled because at this point the
 * user has created an OK descriptor file and the window is no longer 
 * needed.
 */
	sprintf(bfr, "latitude  %s\n", text1);
	fputs(bfr, fp);
	sprintf(bfr, "longitude  %s\n", text2);
	fputs(bfr, fp);
	sprintf(bfr, "elevation  %s\n", text3);
	fputs(bfr, fp);
	sprintf(bfr, "aspect  %s\n", text4);
	fputs(bfr, fp);
	sprintf(bfr, "tilt  %s\n", text5);
	fputs(bfr, fp);
	fclose(fp);
	gtk_widget_set_sensitive(GTK_WIDGET(locale_clear), FALSE);
	gtk_widget_set_sensitive(GTK_WIDGET(locale_save), FALSE);
	gtk_widget_set_sensitive(GTK_WIDGET(locale_close), TRUE);
	return;
}



