// LocalTreeCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "ConsoleApp.h"
#include "LocalTreeCtrl.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);

/////////////////////////////////////////////////////////////////////////////
// CLocalTreeCtrl

CLocalTreeCtrl::CLocalTreeCtrl()
{
}

CLocalTreeCtrl::~CLocalTreeCtrl()
{
}


BEGIN_MESSAGE_MAP(CLocalTreeCtrl, CTreeCtrl)
	//{{AFX_MSG_MAP(CLocalTreeCtrl)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CLocalTreeCtrl message handlers

BOOL CLocalTreeCtrl::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 CTreeCtrl::PreTranslateMessage(pMsg);
}

void CLocalTreeCtrl::DeleteSelectedItem()
{
	IPTxShTreeNode* pnode = (IPTxShTreeNode*)get_SelectedNode();
	if (((CLocalView*)GetParent())->m_pnodeRoot == pnode)
		return;

	if (AfxMessageBox("선택된 폴더를 삭제하시겠습니까?", MB_YESNO) != IDYES)
		return;

	VARIANT_BOOL bFileSystem;

	pnode->get_IsFileSystem(&bFileSystem);
	if (bFileSystem) {
		BSTR bstr;
		pnode->get_PathName(&bstr);
		CString sPath(bstr);
		::SysFreeString(bstr);

		if (sPath == "")
			return;

		if (!DeleteDirectory(sPath))
			return;

		Refresh();
	}
}

BOOL CLocalTreeCtrl::PasteClipboard()
{
	CMainFrame* pmf = (CMainFrame*)AfxGetMainWnd();

	VARIANT_BOOL bFileSystem;

	IPTxShTreeNode *pnode = (IPTxShTreeNode*)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 = sPath;

	return pmf->Download(false);
}