/* 
* 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, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

#include "stdafx.h"
#include "../client/DCPlusPlus.h"
#include "Resource.h"
#include "WinUtil.h"
#include "../client/SimpleXML.h"
#include "../rsx/RsxUtil.h"
#include "../client/Pointer.h"

#include "FileConverterDlg.h"
#define ATTACH(id, var) var.Attach(GetDlgItem(id))
#define is_active(x) x.GetCheck() == BST_CHECKED

namespace dcpp {

FileConverterDlg::~FileConverterDlg() {
	for_each(favoriteHubs.begin(), favoriteHubs.end(), DeleteFunction());
}

LRESULT FileConverterDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) {
	ATTACH(IDC_FC_INPUT, cInput);
	cInput.SetWindowText(_T(""));
	SetDlgItemText(IDC_FC_OUTPUT, Text::toT(Util::getConfigPath()).c_str());

	ATTACH(IDC_FC_FILTER, cUseFilter);
	ATTACH(IDC_FC_HL, cUseHL);
	ATTACH(IDC_FC_STEALTH, cUseEmu);
	ATTACH(IDC_FC_DECODE_PASS, cDecode);

	return 0;
}

LRESULT FileConverterDlg::OnBrowse(UINT /*uMsg*/, WPARAM /*wParam*/, HWND /*lParam*/, BOOL& /*bHandled*/) {
	TCHAR buf[MAX_PATH];
	static const TCHAR types[] = _T("Setting File\0*.xml\0All Files\0*.*\0");

	GetDlgItemText(IDC_FC_INPUT, buf, MAX_PATH);
	tstring x = buf;

	if(WinUtil::browseFile(x, m_hWnd, false, _T(""), types) == IDOK) {
		SetDlgItemText(IDC_FC_INPUT, x.c_str());
		input = x;
	}
	return 0;
}

LRESULT FileConverterDlg::OnBrowseO(UINT /*uMsg*/, WPARAM /*wParam*/, HWND /*lParam*/, BOOL& /*bHandled*/) {
	tstring dir = Text::toT(Util::getConfigPath());
	if(WinUtil::browseDirectory(dir, m_hWnd))
	{
		// Adjust path string
		if(dir.size() > 0 && dir[dir.size() - 1] != '\\')
			dir += '\\';

		SetDlgItemText(IDC_FC_OUTPUT, dir.c_str());
		output = dir + _T("Favorites.xml");
	}
	return 0;
}

void FileConverterDlg::convertFile(const string& path) {
	if(!path.empty()) {
		try {
			SimpleXML xml;
			xml.fromXML(File(path, File::READ, File::OPEN).read());
			
			if(xml.findChild("Favorites")) {
				xml.stepIn();
				loadFile(xml);
				xml.stepOut();
			}
		} catch(const Exception& e) {
			dcdebug("FavoriteManager::loadClientProfiles: %s\n", e.getError().c_str());
		}
	}
}

void FileConverterDlg::loadFile(SimpleXML& aXml) {
	dontSave = true;

#define set_string(x,y) try {\
			f->set##x(aXml.getChildAttrib(y));\
		} catch(...) {\
	}
#define set_int(x,y) try {\
			f->set##x(aXml.getIntChildAttrib(y));\
		} catch(...) {\
	}
#define set_bool(x,y) try {\
			f->set##x(aXml.getBoolChildAttrib(y));\
		} catch(...) {\
	}
//can be worse solution? :P

	aXml.resetCurrentChild();
	if(aXml.findChild("Hubs")) {
		aXml.stepIn();
		while(aXml.findChild("Hub")) {
			Favs* f = new Favs();
			set_string(Name, "Name");
			set_bool(Connect, "Connect");
			set_string(Desc, "Description");
			set_string(Nick,"Nick");
			set_string(Password, "Password");

			if(f->getPassword().empty() && is_active(cDecode)) //probably we should search for other string... :)
				set_string(Password, "UserPassword");

			set_string(Server, "Server");
			set_string(UserDesc, "UserDescription");
			set_string(Encoding, "Encoding");
			set_int(WindowPosX, "WindowPosX");
			set_int(WindowPosY, "WindowPosY");
			set_int(WindowSizeX, "WindowSizeX");
			set_int(WindowSizeY, "WindowSizeY");
			set_int(WindowType, "WindowType");
			set_int(ChatUserSplit, "ChatUserSplit");
			set_bool(Stealth, "StealthMode");
			set_bool(UserListState, "UserListState");
			//set_string(HeaderOrder, "HeaderOrder");
			//set_string(HeaderWidths, "HeaderWidths");
			//set_string(HeaderVisible, "HeaderVisible");
			set_string(FavEmail, "Email");
			set_string(AwayMsg, "AwayMsg");
			set_string(UserProtected, "UserProtected");
			set_bool(CheckOnConnect, "CheckOnConnect");
			set_bool(CheckClients, "CheckClients");
			set_bool(CheckFilelists, "CheckFilelists");
			set_bool(CheckMyInfo, "CheckMyInfo");
			set_bool(HideShare, "HideShare");
			set_bool(CheckFakeShare, "CheckFakeShare");
			set_int(Mode, "Mode");
			set_string(IP, "IP");

			favoriteHubs.push_back(f);
		}
		aXml.stepOut();
	}
	dontSave = false;
	saveFile();
#undef set_string
#undef set_int
#undef set_bool
#ifdef SVN_VER
	MessageBox(_T("Done!"), _T("zK++ Fav Converter"));
#endif
}

void FileConverterDlg::saveFile() {
	if(dontSave)
		return;

	Lock l(cs);
	try {
		SimpleXML xml;

		xml.addTag("Favorites");
		xml.stepIn();

		xml.addTag("Hubs");
		xml.stepIn();

		for(Favs::Iter i = favoriteHubs.begin(); i != favoriteHubs.end(); ++i) {
			xml.addTag("Hub");
			xml.addChildAttrib("Name",				(*i)->getName());
			xml.addChildAttrib("Connect",			(*i)->getConnect());
			xml.addChildAttrib("Description",		(*i)->getDesc());
			xml.addChildAttrib("Nick",				(*i)->getNick(false));

			if(is_active(cDecode))
				xml.addChildAttrib("Password",		RsxUtil::base64_decode((*i)->getPassword()));
			else
				xml.addChildAttrib("Password",		(*i)->getPassword());

			xml.addChildAttrib("Server",			(*i)->getServer());
			xml.addChildAttrib("UserDescription",	(*i)->getUserDesc());
			xml.addChildAttrib("Encoding",			(*i)->getEncoding());
			xml.addChildAttrib("Mode",				Util::toString((*i)->getMode()));
			xml.addChildAttrib("IP",				(*i)->getIP());
			xml.addChildAttrib("WindowPosX",		(*i)->getWindowPosX());
			xml.addChildAttrib("WindowPosY",		(*i)->getWindowPosY());
			xml.addChildAttrib("WindowSizeX",		(*i)->getWindowSizeX());
			xml.addChildAttrib("WindowSizeY",		(*i)->getWindowSizeY());
			xml.addChildAttrib("WindowType",		(*i)->getWindowType());
			xml.addChildAttrib("ChatUserSplit",		(*i)->getChatUserSplit());

			if(is_active(cUseEmu))
				xml.addChildAttrib("StealthMode",	true);
			else
				xml.addChildAttrib("StealthMode",	(*i)->getStealth());

			xml.addChildAttrib("UserListState",		(*i)->getUserListState());
			//xml.addChildAttrib("HeaderOrder",		(*i)->getHeaderOrder());
			//xml.addChildAttrib("HeaderWidths",		(*i)->getHeaderWidths());
			//xml.addChildAttrib("HeaderVisible",		(*i)->getHeaderVisible());
			//set this default
			xml.addChildAttrib("HeaderOrder",		SETTING(HUBFRAME_ORDER));
			xml.addChildAttrib("HeaderWidths",		SETTING(HUBFRAME_WIDTHS));
			xml.addChildAttrib("HeaderVisible",		SETTING(HUBFRAME_VISIBLE));
			xml.addChildAttrib("Email",				(*i)->getFavEmail());
			xml.addChildAttrib("AwayMsg",			(*i)->getAwayMsg());
			xml.addChildAttrib("UserProtected",		(*i)->getUserProtected());
			xml.addChildAttrib("CheckOnConnect",	(*i)->getCheckOnConnect());
			xml.addChildAttrib("CheckClients",		(*i)->getCheckClients());
			xml.addChildAttrib("CheckFilelists",	(*i)->getCheckFilelists());
			xml.addChildAttrib("CheckMyInfo",		(*i)->getCheckMyInfo());
			xml.addChildAttrib("HideShare",			(*i)->getHideShare());
			xml.addChildAttrib("CheckFakeShare",	(*i)->getCheckFakeShare());
	
			if(is_active(cUseFilter))
				xml.addChildAttrib("UseFilter",	true);
			else
				xml.addChildAttrib("UseFilter",		(*i)->getUseFilter());

			xml.addChildAttrib("UseAutosearch",		(*i)->getAutosearch());

			if(is_active(cUseHL))
				xml.addChildAttrib("UseHighLight", true);
			else
				xml.addChildAttrib("UseHighLight",	(*i)->getUseHL());
			xml.addChildAttrib("UsersLimitToUseActions", 0);

		}
		xml.stepOut();

		string fname = output.empty() ? (Util::getConfigPath() + "Favorites.xml") : Text::fromT(output);

		File f(fname + ".tmp", File::WRITE, File::CREATE | File::TRUNCATE);
		f.write(SimpleXML::utf8Header);
		f.write(xml.toXML());
		f.close();
		File::deleteFile(fname);
		File::renameFile(fname + ".tmp", fname);

	} catch(...) {
		//ups...
	}
}

} // namespace dcpp