#include "StdAfx.h"
#include "FileDlgUtil.h"

#include <map>
#include <set>



QString FileDlgUtil::ExtListToDlgFilter(const QString& whole_name, const FileDlgFilterList& list)
{
	QString filter = CreatAllTypeFilter(whole_name, list);

	for (size_t i = 0; i < list.List.size(); ++i)
	{
		const FileDlgFilter& f = list.List[i];
		if (f.Name.isEmpty())
			continue;

		size_t j = i + 1;
		for (; j < list.List.size(); ++j)
		{
			if (list.List[j].Name != f.Name)
				break;
		}

		filter += ";;";
		QString exts = "";
		for (size_t k = i; k < j; ++k)
		{
			const QString& e = list.List[k].Ext;
			exts += QString("*.%1 ").arg(e);
		}
		if (!exts.isEmpty())
			exts.resize(exts.size() - 1);

		filter += ToFilter(f.Name, exts);

		i = j - 1;
	}

	filter += ";;";
	filter += ToFilter("AllFiles", "*.*");
	return filter;
}

QString FileDlgUtil::ToFilter(const QString& name, const QString& ext)
{
	return QString("%1(%2)").arg(name).arg(ext);
}

QString FileDlgUtil::CreatAllTypeFilter(const QString& whole_name, const FileDlgFilterList& list)
{
	QString AllTypes;
	for (const FileDlgFilter& f : list.List)
	{
		AllTypes += QString("*.%1 ").arg(f.Ext);
	}
	if (!AllTypes.isEmpty())
		AllTypes.resize(AllTypes.size() - 1);

	QString filter = ToFilter(whole_name, AllTypes);
	return filter;
}
