/* roadmap_fileselection.c - manage the Widget used in roadmap dialogs.
 *
 * LICENSE:
 *
 *   Copyright 2005 Ehud Shabtai
 *
 *   This file is part of RoadMap.
 *
 *   RoadMap 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.
 *
 *   RoadMap 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 RoadMap; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * SYNOPSYS:
 *
 *   See roadmap_fileselection.h
 */

#include <windows.h>
#include <Commdlg.h>

#include "../roadmap.h"
#include "../roadmap_types.h"
#include "../roadmap_file.h"
#include "../roadmap_fileselection.h"


void roadmap_fileselection_new (const char *title,
								const char *filter,
								const char *path,
								const char *mode,
								RoadMapFileCallback callback)
{
	WCHAR filename[MAX_PATH] = {0};
	WCHAR strFilter[MAX_PATH] = {0};
	LPWSTR title_unicode = ConvertToUNICODE(title);
	BOOL res;

	OPENFILENAME ofn;
	memset(&ofn, 0, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = NULL;
	ofn.lpstrFile = filename;
	ofn.nMaxFile = sizeof(filename) / sizeof(filename[0]);
	ofn.Flags = OFN_EXPLORER;
	ofn.lpstrTitle = title_unicode;
	if (filter != NULL) {
		LPWSTR fltr = ConvertToUNICODE(filter);
		_snwprintf(strFilter, sizeof(strFilter)/sizeof(strFilter[0]),
						TEXT("%s\0%s\0"), fltr, fltr);
		free(fltr);
		ofn.lpstrFilter = strFilter;
	} else {
		ofn.lpstrFilter = TEXT("*.*\0*.*\0");
	}

	if (strchr(mode, 'r') != NULL) {
		ofn.Flags |= OFN_FILEMUSTEXIST;
		res = GetOpenFileName(&ofn);

	} else {
		ofn.Flags |= OFN_OVERWRITEPROMPT;
		res = GetSaveFileName(&ofn);
	}

	free((char*)ofn.lpstrTitle);

	if (res) {
		char *name = ConvertToANSI(filename, CP_ACP);
		(*callback)(name, mode);
		free(name);
	}
}

