#include "StdAfx.h"
#include "mimetypemgr.h"
#include "StringCompare.h"

CMimeTypeMgr::CMimeTypeMgr()
{
}

CMimeTypeMgr::~CMimeTypeMgr(void)
{
}

void CMimeTypeMgr::Load(CWorkspaceAccess serverSetting)
{
	m_serverSetting = serverSetting;
	m_mimeTypeSetting = m_serverSetting.GetAccess("MimeType");
	m_iconTypeSetting = m_serverSetting.GetAccess("IconType");

	LoadMime();
	LoadIcon();
}


/*!
 *	ファイル名からMimetypeを取得
 *
 *	@param name	名前
 *	@return		mimeタイプ
 */
CString CMimeTypeMgr::GetMimeTypeByName(CString name)
{
	int index=name.ReverseFind('.');
	if(index == -1)
		return("application/octet-stream");

	CString ext = name.Mid(index + 1);
	ext = ext.MakeLower();
	for(int i=0;i<m_mimeFilter.GetSize();i++)
		if(ext == m_mimeFilter[i].m_filter)
		{
			//	リストの最適化
			if(i > 5)
			{
				CFilter	swap = m_mimeFilter[i];
				m_mimeFilter.RemoveAt(i);
				m_mimeFilter.InsertAt(0,swap);

				return(swap.m_data);
			}
			return(m_mimeFilter[i].m_data);
		}

	return("application/octet-stream");
}


/*!
 *	ファイル名からアイコンを取得
 *
 *	@param name	名前
 *	@return		mimeタイプ
 */
CString CMimeTypeMgr::GetIconPathByName(CString name)
{
	//	MIMEタイプを取得
	CString mimeType = GetMimeTypeByName(name);
	CString ext;
	int index=name.ReverseFind('.');
	if(index == -1)
	{
		ext = "";
	}
	else
	{
		//	拡張子を取得
		ext = name.Mid(index);
		ext = ext.MakeLower();
	}

	//	キャッシュ
	if(m_oldExt == ext && !ext.IsEmpty())
		return(m_oldType);

	for(int i=0;i<m_iconFilter.GetSize();i++)
	{
		if(ext == m_iconFilter[i].m_filter || CStringCompare::WildCompare(m_iconFilter[i].m_filter,mimeType) || CStringCompare::WildCompare(m_iconFilter[i].m_filter,name))
		{
			m_oldExt = ext;
			m_oldType = m_iconFilter[i].m_data;
			return(m_iconFilter[i].m_data);
		}

	}

	return("");
}

void CMimeTypeMgr::LoadMime(void)
{
	if(m_mimeFilter.GetSize()>0)
		return;

	//	検索
	CStringArray	mimeList;
	int i,len = m_mimeTypeSetting.GetAllSubNode(mimeList);
	for(i=0;i<len;i++)
	{
		CWorkspaceAccess	sub = m_mimeTypeSetting.GetAccess(mimeList[i]);

		CStringArray	extList;
		int j,len2 = sub.GetAllKey(extList);
		CFilter	add;
		add.m_data = mimeList[i];
		for(j=0;j<len2;j++)
		{
			add.m_filter = sub.GetConfig(extList[j],"");
			m_mimeFilter.Add(add);
		}
	}
}


void CMimeTypeMgr::LoadIcon(void)
{
	if(m_iconFilter.GetSize()>0)
		return;

	//	検索
	CStringArray	iconList;
	int i,len = m_iconTypeSetting.GetAllSubNode(iconList);
	for(i=0;i<len;i++)
	{
		CWorkspaceAccess	sub = m_iconTypeSetting.GetAccess(iconList[i]);

		CStringArray	extList;
		int j,len2 = sub.GetAllKey(extList);
		CFilter	add;
		add.m_data = iconList[i];
		for(j=0;j<len2;j++)
		{
			add.m_filter = sub.GetConfig(extList[j],"");
			m_iconFilter.Add(add);
		}
	}
}
