/*
 * config.c
 * Copyright (C) Steffen Pohle 2009 <steffen@gulpe.de>
 * 
 * main.c 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/>.
 */

#if defined(__MINGW32CE__) || defined(_WIN32_WCE) || defined(__MINGW32__)
  #include <windows.h>
  #include <commctrl.h>
  #include <winbase.h>
  #include <shlobj.h>
#endif

#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>

#include "osmroute.h"
#include "system.h"

#if defined(SPOSMROUTE)
  #include "draw.h"
  #include "favorites.h"
#endif


/*
 * some variabled which have to be present in all apps.
 */
struct cfgdata cfg;

#if defined(__MINGW32CE__) || defined(_WIN32_WCE)
	#define CONFIGFILE "config.txt"
#else
	#define CONFIGFILE "config.cfg"
#endif


void config_init () {
	struct stat sb;

	strcpy (cfg.mappath, "map/");
	strcpy (cfg.appdatapath, "data");
	strcpy (cfg.cachepath, "cache/");
	strcpy (cfg.configpath, "");
	strcpy (cfg.logpath, "logs/");
	strcpy (cfg.temppath, "tmposm/");
	strcpy (cfg.gps_device, "");
	cfg.last_scale = 0.001;
	cfg.last_lon = 11.183;
	cfg.last_lat = 48.736;
	cfg.softkeyboard = 1;

		/* Android version will not need config and log path.. */
#if defined(ANDROID)
	strcpy (cfg.appdatapath, "android/assets");
	if (engine.app->activity->internalDataPath == NULL) {
		strncpy (cfg.configpath, "/data/data/de.gulpe.sposmroute/", LEN_FILENAME);
		strncpy (cfg.logpath, "/data/data/de.gulpe.sposmroute/", LEN_FILENAME);
	}
	else {
		strncpy (cfg.configpath, engine.app->activity->internalDataPath, LEN_FILENAME);
		strncpy (cfg.logpath, engine.app->activity->internalDataPath, LEN_FILENAME);
	}
/*    std::string dataPath(internalPath);                               
    // internalDataPath points directly to the files/ directory                                  
    std::string configFile = dataPath + "/app_config.xml";
*/
#else
		/* windows ce version */
 #if defined(__MINGW32CE__) || defined(_WIN32_WCE)
	strcpy (cfg.mappath, "\\Storage Card\\map\\");
	strcpy (cfg.configpath, "\\My Documents\\wOSMroute\\");
	strcpy (cfg.logpath, "\\My Documents\\wOSMroute\\Logdir\\");
 #endif

		/* windows version */
 #if defined(__MINGW32__) && !defined(__MINGW32CE__) && !defined(_WIN32_WCE)
	TCHAR szPath[MAX_PATH];
	if(SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, 0, szPath))) {
		snprintf (cfg.configpath, LEN_FILENAME, "%s\\wOSMroute\\", szPath);
		snprintf (cfg.logpath, LEN_FILENAME, "%s\\wOSMroute\\Logdir\\", szPath);
	}
 #endif
		/* linux version */
 #if !defined(__MINGW32CE__) && !defined(_WIN32_WCE) && !defined(__MINGW32__)
	char *hd;
	
    if ((hd = getenv ("HOME")) == NULL) {
        /* Homedir konnte nicht ermittelt werden. */
		strcpy (cfg.configpath, ".OSMroute/");
		strcpy (cfg.logpath, ".OSMroute/Logdir/");
    }
    else {
		snprintf (cfg.configpath, LEN_FILENAME, "%s/.OSMroute/", hd);
		snprintf (cfg.logpath, LEN_FILENAME, "%s/.OSMroute/Logdir/", hd);
	}
 #endif

	d_print_init();
	if (stat(cfg.configpath, &sb) == -1) {
		char fn[LEN_FILENAME];
		strncpy (fn, cfg.configpath, LEN_FILENAME);
		fn[strlen(fn)-1] = 0;
		d_printf ("create config dir:%s", fn);
 #if !defined(__MINGW32CE__) && !defined(_WIN32_WCE) && !defined(__MINGW32__)
		mkdir (fn, 0755);
 #else
		mkdir (fn);
 #endif
	}
#endif

	config_load ();

	if (stat(cfg.logpath, &sb) == -1) {
		char fn[LEN_FILENAME];
		strncpy (fn, cfg.logpath, LEN_FILENAME);
		fn[strlen(fn)-1] = 0;
		d_printf ("create log dir:%s", fn);
#if !defined(__MINGW32CE__) && !defined(_WIN32_WCE) && !defined(__MINGW32__)
		mkdir (fn, 0755);
#else
		mkdir (fn);
#endif
	}

	if (stat(cfg.mappath, &sb) == -1) {
		char fn[LEN_FILENAME];
		strncpy (fn, cfg.mappath, LEN_FILENAME);
		fn[strlen(fn)-1] = 0;
		d_printf ("create map dir:%s", fn);
#if !defined(__MINGW32CE__) && !defined(_WIN32_WCE) && !defined(__MINGW32__)
		mkdir (fn, 0755);
#else
		mkdir (fn);
#endif
	}

	config_save ();

#if defined(SPOSMROUTE)
	if (cfg.gps_flags) SETFLAG(gpsflags, GPSF_LOG);
	else DELFLAG(gpsflags, GPSF_LOG);

	if (cfg.debug) SETFLAG(view_flags, DRAW_DEBUG);
	else DELFLAG(view_flags, DRAW_DEBUG);
#endif
};


/*
 * load config files
 */
void config_load () {
	char filename[LEN_FILENAME];
    char buf[1024];
    char *findit, *keyword, *value;
    int i;
	FILE *f;
	
	sprintf (filename, "%s%s", cfg.configpath, CONFIGFILE);
	d_printf ("load config file:%s", filename);
	f =  fopen (filename, "r");
	if (f) {
		while (fgets (buf, sizeof (buf), f) != NULL) {
			d_printf ("config file line:%s", buf);
			findit = strchr (buf, '\n');
			if (findit) findit[0] = '\0';
			if (buf[0] == '\0') continue;

			keyword = buf;
			while (isspace (*keyword)) keyword++;

			value = strchr (buf, '=');
			if (value == NULL) continue;

			*value = 0;
			value++;
			while (*value == ' ') value++;
			while (keyword[strlen (keyword) - 1] == ' ') keyword[strlen (keyword) - 1] = 0;
			while (value[strlen (value) - 1] == ' ') value[strlen (value) - 1] = 0;
			if (strlen (value) == 0) continue;

			for (i = 0; i < (int) strlen (keyword); i++)
				keyword[i] = tolower (keyword[i]);
			
			if (!strcmp (keyword, "mappath")) 
				strncpy (cfg.mappath, value, LEN_FILENAME);
			if (!strcmp (keyword, "temppath")) 
				strncpy (cfg.temppath, value, LEN_FILENAME);
			if (!strcmp (keyword, "cachepath"))
				strncpy (cfg.cachepath, value, LEN_FILENAME);
			if (!strcmp (keyword, "logpath")) 
				strncpy (cfg.logpath, value, LEN_FILENAME);
#if defined(SPOSMROUTE)
			if (!strcmp (keyword, "last_lon"))
				cfg.last_lon = atof (value);
	        if (!strcmp (keyword, "last_lat"))
				cfg.last_lat = atof (value);
	        if (!strcmp (keyword, "last_scale"))
				cfg.last_scale = atof (value);
			if (!strcmp (keyword, "gps_device")) 
				strncpy (cfg.gps_device, value, LEN_FILENAME);
			if (!strcmp (keyword, "gps_flags")) {
				cfg.gps_flags = atoi (value);
			}
			if (!strcmp (keyword, "debug")) {
				cfg.debug = atoi (value);		
			}
			if (!strcmp (keyword, "softkeyboard")) {
				cfg.softkeyboard = atoi (value);		
			}
#endif
		}
		fclose (f);
	}

	d_printf ("configpath: %s", cfg.configpath);
	d_printf ("   mappath: %s", cfg.mappath);
	d_printf ("   logpath: %s", cfg.logpath);
	d_printf (" cachepath: %s", cfg.cachepath);
	d_printf ("  temppath: %s", cfg.temppath);
};


/*
 * save config file
 */
void config_save () {
	char filename[LEN_FILENAME];
	FILE *f;

	sprintf (filename, "%s%s", cfg.configpath, CONFIGFILE);
	d_printf ("save config file:%s", filename);
	f = fopen (filename, "w");
	if (f) {
		fprintf (f, "# config file for osmroute\n\n");
		fprintf (f, "mappath=%s\n", cfg.mappath);
		fprintf (f, "logpath=%s\n", cfg.logpath);
		fprintf (f, "cachepath=%s\n", cfg.cachepath);
		fprintf (f, "temppath=%s\n", cfg.temppath);
#if defined(SPOSMROUTE)
		fprintf (f, "last_lon=%f\n", cfg.last_lon);
		fprintf (f, "last_lat=%f\n", cfg.last_lat);
		fprintf (f, "last_scale=%f\n", cfg.last_scale);

		fprintf (f, "gps_flags=%d\n", cfg.gps_flags);
		fprintf (f, "gps_device=%s\n", cfg.gps_device);
		fprintf (f, "debug=%d\n", cfg.debug);
		fprintf (f, "softkeyboard=%d\n", cfg.softkeyboard);
#endif
		fclose (f);
	}
};

