#include "stdafx.h"
#include "FileList.h"

#ifdef _DEBUG
#include <iostream>
#endif

#include "SqliteUtil.h"
#include "MD5Checksum.h"
#include "utils.h"
#include "SqliteUtil.h"
#include <algorithm> 
#include <windows.h>
#include <string>

CFileList::CFileList(void)
{
	
}

CFileList::~CFileList(void)
{
}

BOOL CFileList::list_files(LPCTSTR pstr) {
	CFileFind finder;
	CStringW strWildcard(pstr);
	strWildcard += _T("\\*.*");
	BOOL bWorking = finder.FindFile(strWildcard);
	BOOL ret = false;
	char newPath[MAX_PATH_LENGTH];

	while (bWorking) {
		bWorking = finder.FindNextFile();
		if (finder.IsDots()) {
			continue;
		}

		if (finder.IsDirectory()) {
			CStringW str = finder.GetFilePath();
			list_files(str);
		} else {
			CString str = finder.GetFileName();
			
			if (-1 != str.Find(_T("jpg"))){
				if (CSqliteUtil::instance()->exist(finder.GetFilePath())) {
					continue;
				}

				DEBUG_OUTW(finder.GetFilePath().GetString());
				if (rename_files(finder.GetFilePath(), newPath)) {
					mFiles.push_back(CString(newPath));
				}
			}
		}
	}

	finder.Close();

	sort_files();

	return mFiles.empty();
}

bool SortByName(const CString &v1, const CString &v2)
{  
	return v1 < v2;//ÉýÐòÅÅÁÐ
}

bool SortByCreateTime(const CString &v1, const CString &v2)
{
	CFileStatus status;
	CFile::GetStatus(v1.GetString(), status);
	CTime t1 = status.m_atime;

	CFile::GetStatus(v2.GetString(), status);
	CTime t2 = status.m_atime;


	return t1 < t2;
}

BOOL CFileList::sort_files()
{
	std::sort(mFiles.begin(), mFiles.end(), SortByCreateTime);

	return true;
}

CString& CFileList::getPath()
{
	CString path("");
	if (mFiles.empty())
		return path;
	else
		return mFiles.at(0);
}

BOOL CFileList::rename_files(const CString& path, char *newPath)
{
	char source[MAX_PATH_LENGTH];

	CString md5sum = CMD5Checksum::GetMD5(path.GetString());
	USES_CONVERSION;
	_snprintf(source, MAX_PATH_LENGTH, "%s", T2A(path));

	std::string oldPath(source);

	size_t pos = oldPath.find_last_of("\\");
	if (std::string::npos == pos) {
		return false;
	}

	DEBUG_OUT("rename_files: "+oldPath);

	memcpy(newPath, source, pos + 1);
	_snprintf(newPath + pos + 1, MAX_PATH_LENGTH - pos - 1, "%s.jpg", T2A(md5sum));
	DEBUG_OUT("rename_files: "+std::string(newPath));

	if (0 == strcmp(source, newPath)) {
		return false;
	}

	if (0 != rename(source, newPath)) {
		return false;
	}

	return true;
}
