/** 
 * @file KofFile.h
 * @brief 򿪼ļ
 * @author ޻ 
 * @date 2012-4-3
 * @details 򿪼ANSIUTF-8UTF-8NoBomUTF-16BEUTF-16LEWindowsUNIXMacͬзµıļ
 */ 
#pragma once

/** ĵʽ */
enum FileFormatType{
	WIN_FORMAT,		/**< Windowsʽĵ */
	UNIX_FORMAT,
	MAC_FORMAT
};

/** ĵ */
enum FileEncodeType{
	ANSI_ENCODE = 0,	/**< ANSI */
	UTF8_ENCODE,
	UTF8NB_ENCODE,
	UTF16BE_ENCODE,
	UTF16LE_ENCODE,
	END_ENCODE
};

/** Ϣ */
const UINT MAX_ERROR_MSG = 1024;

class CKofFile
{
public:
	CKofFile(void);
	~CKofFile(void);

	/**
	 * ָļļݵַ
	 * @param LPCTSTR lpszFileName ļ
	 * @param CString & strFileText ַ
	 * @return BOOL Ƿ򿪳ɹ
	 */
	BOOL OpenFile(LPCTSTR lpszFileName, CString &strFileText);

	/**
	 * ָݵָļļ
	 * @param LPCTSTR lpszFileName ļ 
	 * @param LPCTSTR lpszFileText ַ
	 * @return BOOL Ƿ񱣴ɹ
	 */
	BOOL SaveFile(LPCTSTR lpszFileName, LPCTSTR lpszFileText);
	
	/**
	 * ȡĴϢ
	 * @return LPCTSTR شϢָ
	 */
	LPCTSTR GetLastErrorMsg(){return m_szErrorMsg;} 

	
	/**
	 * ȡǰ򿪵ļĵʽ
	 * @return FileFormatType ļĵʽ
	 */
	FileFormatType GetFileFormatType(){return m_FormatType;}
	
	/**
	 * ȡǰ򿪵ļĵ
	 * @return FileEncodeType ļĵ
	 */
	FileEncodeType GetFileEncodeType(){return m_EncodeType;}

	/**
	* ȡǰ򿪵ļĵҳ
	* @return UINT ļĵҳ
	*/
	UINT GetCodepage(){ return m_nCodepage; }

	/**
	* õǰ򿪵ļĵҳ
	* @param UINT nCodePage ôҳ
	*/
	void SetCodepage(UINT nCodePage);

	/**
	* Դҳȡ
	* @param UINT nCodePage ҳ
	*/
	FileEncodeType GetFileEncodeTypeByCodepage(UINT nCodePage);

	/**
	 * ı
	 * @param FileEncodeType encodeType
	 * @return BOOL 
	 */
	BOOL ChangeFileEncodeType(FileEncodeType encodeType);

	/**
	* ı
	* @param FileEncodeType encodeType
	* @return BOOL
	*/
	BOOL ChangeCodepage(UINT nCodePage, CString &strFileText);

	/**
	* ȡַ
	* @return LPCTSTR شϢָ
	*/
	LPCTSTR GetCodepageString();

protected:
	void DetermineEncodeType(LPSTR lpszFileBuf, DWORD dwFileSize);
	void DetermineFormatType(LPSTR lpszFileBuf, DWORD dwFileSize);
	void ConvertEncodeToTChar(LPSTR lpszFileBuf, DWORD dwFileSize, CString &strFileText);
	void ConvertFormatToTChar(CString &strFileText);
	void ProcessTCharFormat(LPSTR lpszFileText, DWORD &dwFileSize);
	void SaveFileText(CFile &file, LPSTR lpszFileBuf, DWORD dwFileSize);
	void BigEndianSwapLittleEndian(LPSTR lpszFileBuf, DWORD dwFileSize);
	BOOL IsTextUtf8(LPCSTR lpszFileBuf, DWORD dwFileSize);
	void SetLastErrorMsg(LPCTSTR lpszErrorMsg){lstrcpy(m_szErrorMsg, lpszErrorMsg);}
	void DetectCodepage(LPSTR lpszFileBuf, DWORD dwFileSize);
	UINT GetEncodingFromString(const char *encodingAlias);

private:
	FileFormatType m_FormatType;
	FileEncodeType m_EncodeType;
	TCHAR m_szErrorMsg[MAX_ERROR_MSG];
	UINT m_nSkip;
	UINT m_nCodepage;
	static const UCHAR m_EncodeBoms[END_ENCODE][3];
};
