// LocalListCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "ConsoleApp.h"
#include "LocalListCtrl.h"

#include "MainFrm.h"
#include "LocalView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

BOOL DeleteDirectory(CString sDirectory);

/////////////////////////////////////////////////////////////////////////////
// CLocalListCtrl

CLocalListCtrl::CLocalListCtrl()
{
}

CLocalListCtrl::~CLocalListCtrl()
{
}


BEGIN_MESSAGE_MAP(CLocalListCtrl, CListCtrl)
	//{{AFX_MSG_MAP(CLocalListCtrl)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CLocalListCtrl message handlers

BOOL CLocalListCtrl::PreTranslateMessage(MSG* pMsg)
{
	CMainFrame *pmf = (CMainFrame *)AfxGetMainWnd();

	switch (pMsg->message)
	{
	case WM_SETFOCUS:
	case WM_LBUTTONDOWN:
	case WM_RBUTTONDOWN:
		pmf->SetFocus(this);
		break;
	case WM_KEYDOWN:
		if (GetKeyState(VK_CONTROL) & 128) {
			if (pMsg->wParam == VK_D) {
				DeleteSelectedItem();
				return TRUE;
			}
			else if (pMsg->wParam == VK_V) {
				if (PasteClipboard())
					return TRUE;
			}
		}
		break;
	}

	return CListCtrl::PreTranslateMessage(pMsg);
}

void CLocalListCtrl::DeleteSelectedItem()
{
	if (AfxMessageBox("선택된 파일을 삭제하시겠습니까?", MB_YESNO) != IDYES)
		return;

	IPTxShListItems *pitems = (IPTxShListItems *)get_Items();

	long nTotalCount;

	pitems->get_Count(&nTotalCount);

	VARIANT_BOOL bFileSystem;

	IPTxShTreeNode *pnode = (IPTxShTreeNode*)((CLocalView*)GetParent())->m_tree.get_SelectedNode();
	pnode->get_IsFileSystem(&bFileSystem);
	if (bFileSystem) {
		IPTxShListItem *pitem;
		for (int i = 0; i < nTotalCount; i++) {
			pitems->get_Item(i, &pitem);

			VARIANT_BOOL bSelected;
			pitem->get_Selected(&bSelected);
			if (!bSelected)
				continue;

			BSTR bstr;
			pitem->get_PathName(&bstr);
			CString sPath(bstr);
			::SysFreeString(bstr);

			if (sPath == "")
				continue;

			DWORD dwAttr = GetFileAttributes(sPath);
			if (dwAttr == INVALID_FILE_ATTRIBUTES)
				continue;

			if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
				DeleteDirectory(sPath);
			else
				DeleteFile(sPath);
		}

		Refresh();
	}
}

BOOL CLocalListCtrl::PasteClipboard(CString sFolder)
{
	CMainFrame* pmf = (CMainFrame*)AfxGetMainWnd();

	CLocalTreeCtrl* ptree = &((CLocalView*)GetParent())->m_tree;

	VARIANT_BOOL bFileSystem;

	IPTxShTreeNode *pnode = (IPTxShTreeNode*)ptree->get_SelectedNode();
	pnode->get_IsFileSystem(&bFileSystem);
	if (!bFileSystem)
		return FALSE;

	BSTR bstr;
	pnode->get_PathName(&bstr);
	CString sPath(bstr);
	::SysFreeString(bstr);

	COleDataObject odo;

	if (odo.AttachClipboard() && odo.IsDataAvailable(CF_HDROP))
		return ((CLocalView*)GetParent())->CopyClipboard(odo, sPath);

	if (pmf->m_cbs == CBS_NONE)
		return FALSE;

	if (pmf->m_saDragSource.GetCount() == 0)
		return FALSE;

	pmf->m_sDragTarget = sFolder == "" ? sPath : sFolder;

	return pmf->Download(false);
}