/*******************************************************************

Copyright (c) 2004 Open Mobile Alliance, Ltd.  All Rights Reserved.

This software is made available under the usage and distribution terms 
covered by the Common Public License 1.0 and by using this software you
are bound by the terms and conditions of the same.

EXCEPT AS EXPRESSLY SET FORTH IN THE COMMON PUBLIC LICENSE,
THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, 
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, 
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
   
Each recipient is solely responsible for determining the 
appropriateness of using and distributing this program and assumes 
all risks associated with its exercise of rights under the Common 
Public License, including but not limited to the risks and 
costs of program errors, compliance with applicable laws, 
damage to or loss of data, programs or equipment, and 
unavailability or interruption of operations.

********************************************************************/

// LeftPane.cpp : implementation file
//

#include "stdafx.h"
#include "SCTS3DevMan.h"
#include "SessionPane.h"
#include "LeftPane.h"
#include "LogPane.h"
#include "ErrorLogPane.h"
#include "IdlePane.h"
#include "TreePane.h"
#include "TestPane.h"
#include "DMAccountPane.h"
#include "ConRefPane.h"
#include "CommandsPane.h"
#include "ClientDevicePane.h"
#include "ServerDevicePane2.h"
#include "atlbase.h"
#include "UIADisplay.h"
#include "UIAChoice.h"
#include "UIAInput.h"
#include "UIAConfirmation.h"
#include "SctsDevManNotificationSession.h"
#include "NotifyAddress.h"

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

/* Callbacks */
static int interactionAlert(char *deviceID,int alertCode,std::list<char *>&items,int maxDT,int minDT,int maxLen,char *dr,char et,char it)
{
	SctsSemaphore lock(0,1);
	CDialog *dialog;
	CString input=dr?dr:"";
	bool conf;
	int choice=0;
    std::list<int> choices;
	int statusCode=408;
	UINT dialogID;
	switch (alertCode)
	{
	case 1100:
		dialog=new CUIADisplay(lock,deviceID,items.front());
		dialogID=IDD_UIADISPLAY;
		break;
	case 1101:
		dialog=new CUIAConfirmation(lock,deviceID,items.front(),conf);
		dialogID=IDD_UIACONFIRMATION;
		break;
	case 1102:
		dialog=new CUIAInput(lock,deviceID,items.front(),input,et,it,maxLen);
		dialogID=IDD_UIAINPUT;
		break;
	case 1103:
		items.push_front(deviceID);
		dialog=new CUIAChoice(lock,items,choice);
		dialogID=IDD_UIACHOICE;
		break;
    /*
     * Change to support Multi Choices. 
     */
	case 1104:
		items.push_front(deviceID);
		dialog=new CUIAChoice(lock,items,choices);
		dialogID=IDD_UIACHOICE;
		break;
	default:
		SCTSASSERT(false);
	}
	SendMessage(mainPane->m_hWnd,WM_DISPLAYUIA,(WPARAM)dialog,(LPARAM)dialogID);
	if (lock.Lock(maxDT>0?maxDT*1000:-1))
	{
		statusCode=200;
		if (alertCode==1101 && !conf) statusCode=304;
	}
	else
		SendMessage(mainPane->m_hWnd,WM_DESTROYUIA,(WPARAM)dialog,0);
	if (alertCode==1102)
		items.push_back(sctsStrdup(input));
	if (alertCode==1103)
	{
		char buffer[10];
		items.push_back(sctsStrdup(sctsInt2Str(choice,buffer,10)));
	}
    /*
     * Change to support Multi Choices. 
     */
	if (alertCode==1104)
	{
		char buffer[10];
        items.clear();
        for (std::list<int>::iterator it=choices.begin();it!=choices.end();++it)
        {
		    items.push_back(sctsStrdup(sctsInt2Str(*it,buffer,10)));
        }
	}

	return statusCode;
}

static void addSession(SctsDMSession *session)
{
	/* 
	Update the application time stamp so that only relevent files are listed when
	reporting a bug, the time stamp should be updated only if no active sessions
	are running.
	*/
	CRegKey key;
	CString tempStr;
	if (!SctsThread::GetThreadCount(SESSION_THREAD))
	{
		/* Open the main key */
		tempStr="SOFTWARE\\SyncML Conformance Test Suite\\";
		tempStr+=SCTS_VERSION;
		if (key.Open(HKEY_LOCAL_MACHINE,tempStr)==ERROR_SUCCESS)
		{
			/* Update the time stamp */
			appTimeStamp=time(0);
			SCTSASSERT(key.SetValue(appTimeStamp,"AppTimestamp")==ERROR_SUCCESS);
			/* Close key */
			key.Close();
		}
	}
	::SendMessage(mainPane->m_hWnd,WM_ADDSESSION,(WPARAM)session,0);
}

static void sessionComplete(SctsDMSession *session)
{
	if (!session->uiData) return;
	::SendMessage(mainPane->m_hWnd,WM_SESSIONCOMPLETE,(WPARAM)session,0);
}

static void addClientDevice(SctsDMClientDevice *device)
{
	::SendMessage(mainPane->m_hWnd,WM_ADDCLIENTDEV,(WPARAM)device,0);
}

static void addServerDevice(SctsDMServerDevice *device)
{
	::SendMessage(mainPane->m_hWnd,WM_ADDSERVERDEV,(WPARAM)device,0);
}

static void removeClientDevice(SctsDMClientDevice *device)
{
	::SendMessage(mainPane->m_hWnd,WM_REMCLIENTDEV,(WPARAM)device,0);
}

static void removeServerDevice(SctsDMServerDevice *device)
{
	::SendMessage(mainPane->m_hWnd,WM_REMSERVERDEV,(WPARAM)device,0);
}
/////////////////////////////////////////////////////////////////////////////
// CLeftPane dialog
CLeftPane::CLeftPane(CWnd* pParent /*=NULL*/)
	: CDialog(CLeftPane::IDD, pParent)
{
	//{{AFX_DATA_INIT(CLeftPane)
	//}}AFX_DATA_INIT
}


void CLeftPane::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CLeftPane)
	DDX_Control(pDX, IDC_SESSIONTREE, m_sessionTree);
	DDX_Control(pDX, IDC_ACCOUNTTREE, m_accountTree);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CLeftPane, CDialog)
	//{{AFX_MSG_MAP(CLeftPane)
	ON_WM_SIZE()
	ON_NOTIFY(TVN_SELCHANGED, IDC_ACCOUNTTREE, OnSelchangedAccounttree)
	ON_NOTIFY(TVN_SELCHANGING, IDC_ACCOUNTTREE, OnSelchangingAccounttree)
	ON_WM_DESTROY()
	ON_NOTIFY(TVN_SELCHANGING, IDC_SESSIONTREE, OnSelchangingSessiontree)
	ON_NOTIFY(TVN_SELCHANGED, IDC_SESSIONTREE, OnSelchangedSessiontree)
	ON_WM_TIMER()
	ON_NOTIFY(TVN_DELETEITEM, IDC_SESSIONTREE, OnDeleteitemSessiontree)
	ON_NOTIFY(TVN_DELETEITEM, IDC_ACCOUNTTREE, OnDeleteitemAccounttree)
	ON_COMMAND(ID_NOTIFY_SENDNOTIFICATION, OnNotifySendnotification)
	ON_COMMAND(ID_NOTIFY_MAKENOTIFIABLE, OnNotifyMakenotifiable)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CLeftPane message handlers
BOOL CLeftPane::OnInitDialog() 
{
	SctsComponentUICallbacks uic;
	CDialog::OnInitDialog();
	paneRatio=0.66;

	/* Session image list */
	sessionImgList.Create(16,16,ILC_MASK | ILC_COLOR8,11,0);
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION0)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION5)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION4)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION3)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION2)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION1)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CHANGELOG)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_ERR)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSIONERR)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_IN)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_OUT)));
	sessionImgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SESSION1)));
	
	/* Load image list */
	imgList.Create(16,16,ILC_MASK | ILC_COLOR8,20,0);
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CDEVICE)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SDEVICE)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CDEV)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SDEV)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TEST)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_ACC)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CON)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CMD)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TREE)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TREE)));

	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CDEVICESEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SDEVICESEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CDEVSEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_SDEVSEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TESTSEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_ACCSEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CONSEL)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_CMD)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TREE)));
	imgList.Add(LoadIcon(AfxGetResourceHandle(),MAKEINTRESOURCE(IDI_TREE)));
	
	m_accountTree.SetImageList(&imgList,TVSIL_NORMAL);
	m_sessionTree.SetImageList(&sessionImgList,TVSIL_NORMAL);

	m_accountTree.ModifyStyle(0,WS_SIZEBOX | WS_CAPTION);
	m_accountTree.SetWindowText("Accounts");
	m_sessionTree.ModifyStyle(0,WS_SIZEBOX | WS_CAPTION);
	m_sessionTree.SetWindowText("Sessions");
	navigator=&m_accountTree;
	
	clientDevices=m_accountTree.InsertItem("Client Devices",NODE_CDEV,NODE_CDEV+NODE_COUNT);
	serverDevices=m_accountTree.InsertItem("Server Devices",NODE_SDEV,NODE_SDEV+NODE_COUNT);

	/* Set component callbacks */
	sctsMemset(&uic,0,sizeof(SctsComponentUICallbacks));
	uic.addSession=addSession;
	uic.removeSession=sessionComplete;
	uic.addClientDevice=addClientDevice;
	uic.addServerDevice=addServerDevice;
	uic.removeClientDevice=removeClientDevice;
	uic.removeServerDevice=removeServerDevice;
	uic.interactionAlert=interactionAlert;
	sctsSetComponentUIC(&uic);

	/* Load acounts */
	FILE *fp=0;
    if(appPath.GetLength())
	    fp=fopen(appPath,"rb");
	if (fp)
	{
		SctsDMDevice::LoadAll(fp);
		fclose(fp);
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}


BOOL CLeftPane::PreTranslateMessage(MSG* pMsg) 
{
	/* Capture paint message for account tree */
	if (pMsg->hwnd==m_accountTree.m_hWnd)
	{
		RECT rect;
		m_accountTree.GetWindowRect(&rect);
		paneRatio=rect.bottom-rect.top;
		GetClientRect(&rect);
		paneRatio/=rect.bottom;
		m_sessionTree.MoveWindow(0,(int)(rect.bottom*paneRatio),rect.right,(int)(rect.bottom*(1-paneRatio)));
	}

	/* Allow only sizing of the bottom border of the account tree */
	if (pMsg->hwnd==m_accountTree.m_hWnd && pMsg->message==WM_NCLBUTTONDOWN && pMsg->wParam>=HTLEFT && pMsg->wParam<=HTBOTTOMRIGHT && pMsg->wParam!=HTBOTTOM) return TRUE;
	if (pMsg->hwnd==m_sessionTree.m_hWnd && pMsg->message==WM_NCLBUTTONDOWN && pMsg->wParam>=HTLEFT && pMsg->wParam<=HTBOTTOMRIGHT) return TRUE;
	if ((pMsg->hwnd==m_accountTree.m_hWnd || pMsg->hwnd==m_sessionTree.m_hWnd) && 
		(pMsg->message==WM_NCLBUTTONDOWN || pMsg->message==WM_NCLBUTTONDBLCLK) && 
		pMsg->wParam==HTCAPTION) return TRUE;

	/* Disable ESC  and Enter */
	if (pMsg->message==WM_KEYDOWN && (pMsg->wParam==VK_ESCAPE || pMsg->wParam==VK_RETURN)) return TRUE;
	
	/* Notification right click */
	if (pMsg->message==WM_RBUTTONDOWN && pMsg->hwnd==m_accountTree.m_hWnd)
	{
		int nodeType;
		int tempInt;
		HTREEITEM item;
		POINT point={pMsg->lParam&0xFFFF, pMsg->lParam>>16};
		item=m_accountTree.HitTest(point);
		m_accountTree.GetItemImage(item,nodeType,tempInt);
		if (nodeType==NODE_CLIENTDEV || nodeType==NODE_SERVERDEV)
		{
			CMenu menu;
			VERIFY(menu.LoadMenu(IDR_MENUS));
			CMenu *notifyMenu=menu.GetSubMenu(2);
			ASSERT(notifyMenu != NULL);
			m_accountTree.ClientToScreen(&point);
			notifyMenu->EnableMenuItem(ID_NOTIFY_SENDNOTIFICATION,nodeType==NODE_SERVERDEV?MF_ENABLED:MF_GRAYED);
			notifyMenu->EnableMenuItem(ID_NOTIFY_MAKENOTIFIABLE,nodeType!=NODE_SERVERDEV?MF_ENABLED:MF_GRAYED);
			if (item)
			{
				m_accountTree.SelectItem(item);
				notifyMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,point.x,point.y , this);
			}
		}
	}


	return CDialog::PreTranslateMessage(pMsg);
}

void CLeftPane::OnSize(UINT nType, int cx, int cy) 
{
	CDialog::OnSize(nType, cx, cy);
	if (m_accountTree.m_hWnd && m_sessionTree.m_hWnd)
	{
		RECT rect;
		GetClientRect(&rect);
		m_accountTree.MoveWindow(0,0,rect.right,(int)(rect.bottom*paneRatio));
		m_sessionTree.MoveWindow(0,(int)(rect.bottom*paneRatio),rect.right,(int)(rect.bottom*(1-paneRatio)));
	}
}


void CLeftPane::OnSelchangedAccounttree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	HTREEITEM currentItem=m_accountTree.GetSelectedItem();
	DWORD data;
	int nodeType;
	int tempInt;
	CMenu *menu=mainPane->GetMenu()->GetSubMenu(0);
	*pResult = 0;
	ClearPanes();
	/* Disable menu */

	/* Disable toolbar */
	mainPane->GetDlgItem(IDC_DEVADD)->EnableWindow(FALSE);
	mainPane->GetDlgItem(IDC_DEVDEL)->EnableWindow(FALSE);

	if (!currentItem) 
	{
		mainPane->currentRightChildPane=new CIdlePane();
		mainPane->currentRightChildPane->Create(IDD_IDLEPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic();
		mainPane->deleteChild=true;
		return;
	}
	m_sessionTree.SelectItem(0);
	m_accountTree.GetItemImage(currentItem,nodeType,tempInt);
	/* Get current account */
	
	/* Get the current device */

	/* Create the right pane */
	mainPane->deleteChild=true;
	data=m_accountTree.GetItemData(currentItem);
	switch (nodeType)
	{
	case NODE_SERVERDEV:
		mainPane->currentRightChildPane=new CServerDevicePane2((SctsDMServerDevice *)data);
		mainPane->currentRightChildPane->Create(IDD_SERVERDEVICEPANE2,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic();
		break;
	case NODE_CLIENTDEV:
		mainPane->currentRightChildPane=new CClientDevicePane((SctsDMClientDevice *)data);
		mainPane->currentRightChildPane->Create(IDD_CLIENTDEVICEPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic();
		break;
	case NODE_TEST:
		mainPane->currentRightChildPane=new CTestPane((SctsDMTester *)data);
		mainPane->currentRightChildPane->Create(IDD_TESTPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		break;
	case NODE_CDEVTREE:
		mainPane->currentRightChildPane=(CTreePane *)((SctsDMClientDevice *)data)->uiCallbackData;
		mainPane->currentRightChildPane->ShowWindow(SW_SHOW);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		mainPane->deleteChild=false;
		break;
	case NODE_SDEVTREE:
		mainPane->currentRightChildPane=(CTreePane *)((SctsDMServerDevice *)data)->uiCallbackData;
		mainPane->currentRightChildPane->ShowWindow(SW_SHOW);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		mainPane->deleteChild=false;
		break;
	case NODE_ACCOUNTS:
        if (!((SctsDMTree *)data)->IsServerTree())
        {
            SctsDMClientDevice *cliDev = (SctsDMClientDevice *)(SctsDMTree *)data;
            if (cliDev->dmAccPath && cliDev->FindDMNode(cliDev->dmAccPath))
            {
			    mainPane->currentRightChildPane=new CDMAccountPane((SctsDMTree *)data);
			    mainPane->currentRightChildPane->Create(((SctsDMTree *)data)->IsServerTree()?IDD_DMACCPANESERVER:IDD_DMACCPANE,mainPane->currentRightPane);
			    mainPane->currentRightPane->SetResizeLogic();
            }
        }
        else
        {
            SctsDMServerDevice *srvDev = (SctsDMServerDevice *)(SctsDMTree *)data;
            if (srvDev->dmAccPath && srvDev->FindDMNode(srvDev->dmAccPath))
            {
			    mainPane->currentRightChildPane=new CDMAccountPane((SctsDMTree *)data);
			    mainPane->currentRightChildPane->Create(((SctsDMTree *)data)->IsServerTree()?IDD_DMACCPANESERVER:IDD_DMACCPANE,mainPane->currentRightPane);
			    mainPane->currentRightPane->SetResizeLogic();
            }
        }
		break;
	case NODE_CONREF:
        if (!((SctsDMTree *)data)->IsServerTree())
        {
            SctsDMClientDevice *cliDev = (SctsDMClientDevice *)(SctsDMTree *)data;
            SctsDMNode *node = ((SctsDMTree *)data)->FindDMNode(cliDev->dmAccPath);
		    if (node && ((SctsDMTree *)data)->FindDMNode("Con", node))
		    {
			    mainPane->currentRightChildPane=new CConRefPane("*",(SctsDMTree *)data);
			    mainPane->currentRightChildPane->Create(IDD_CONREFPANE,mainPane->currentRightPane);
			    mainPane->currentRightPane->SetResizeLogic();
		    }
        }
        else
        {
            SctsDMServerDevice *srvDev = (SctsDMServerDevice *)(SctsDMTree *)data;
            SctsDMNode *node = ((SctsDMTree *)data)->FindDMNode(srvDev->dmAccPath);
		    if (node && ((SctsDMTree *)data)->FindDMNode("Con", node))
		    {
			    mainPane->currentRightChildPane=new CConRefPane("*",(SctsDMTree *)data);
			    mainPane->currentRightChildPane->Create(IDD_CONREFPANE,mainPane->currentRightPane);
			    mainPane->currentRightPane->SetResizeLogic();
		    }
        }
		break;
	case NODE_COMMANDS:
		mainPane->currentRightChildPane=new CCommandsPane((SctsDMServerTree *)data);
		mainPane->currentRightChildPane->Create(IDD_COMMANDSPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic();
		break;
	}

	/* Enable the toolbar,menu */
	switch(nodeType)
	{
	case NODE_CLIENTDEV:
	case NODE_SERVERDEV:
		mainPane->GetDlgItem(IDC_DEVDEL)->EnableWindow(TRUE);
	case NODE_CDEV:
	case NODE_SDEV:
		mainPane->GetDlgItem(IDC_DEVADD)->EnableWindow(TRUE);
		break;
	}

	/* Load idle pane if no pane has been loaded */
	if (!mainPane->currentRightChildPane) 
	{
		mainPane->currentRightChildPane=new CIdlePane();
		mainPane->currentRightChildPane->Create(IDD_IDLEPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic();
	}
}

void CLeftPane::OnSelchangingAccounttree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	ClearPanes();
	*pResult=0;
}

void CLeftPane::OnDestroy() 
{
	CDialog::OnDestroy();
	sctsSetComponentUIC(0);
}

void CLeftPane::OnSelchangingSessiontree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	ClearPanes();
	*pResult = 0;
}

void CLeftPane::OnSelchangedSessiontree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	HTREEITEM item;
	*pResult = 0;
	item=m_sessionTree.GetSelectedItem();
	if (!item) return;
	m_accountTree.SelectItem(0);
	ClearPanes();
	if (!m_sessionTree.GetParentItem(item))
	{
		mainPane->currentRightChildPane=(CSessionPane *)m_sessionTree.GetItemData(item);
		mainPane->currentRightChildPane->ShowWindow(SW_SHOW);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		mainPane->deleteChild=false;
		return;
	}
	if (m_sessionTree.GetParentItem(m_sessionTree.GetParentItem(item)))
	{
		long *pos=(long *)m_sessionTree.GetItemData(item);
		item=m_sessionTree.GetParentItem(item);
		mainPane->currentRightChildPane=new CLogPane((char *)m_sessionTree.GetItemData(item),*pos,*(pos+1));
		mainPane->currentRightChildPane->Create(IDD_LOGPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		mainPane->deleteChild=true;
		return;
	}
	if (m_sessionTree.GetItemText(item)=="Errors")
	{
		mainPane->currentRightChildPane=new CErrorLogPane((SctsErrorLog *)m_sessionTree.GetItemData(item));
		mainPane->currentRightChildPane->Create(IDD_ERRORLOGPANE,mainPane->currentRightPane);
		mainPane->currentRightPane->SetResizeLogic(false,false);
		mainPane->deleteChild=true;
		return;
	}
	mainPane->currentRightChildPane=new CIdlePane();
	mainPane->currentRightChildPane->Create(IDD_IDLEPANE,mainPane->currentRightPane);
	mainPane->currentRightPane->SetResizeLogic();
	mainPane->deleteChild=true;
	return;
}

void CLeftPane::ClearPanes()
{
	if (!mainPane->currentRightChildPane) return;
	if (mainPane->deleteChild)
	{
		if (mainPane->currentRightChildPane->m_hWnd) SCTSASSERT(mainPane->currentRightChildPane->DestroyWindow());
		delete mainPane->currentRightChildPane;
	}
	else
		mainPane->currentRightChildPane->ShowWindow(SW_HIDE);
	mainPane->currentRightChildPane=0;
}

void CLeftPane::OnTimer(UINT nIDEvent) 
{
	/* Change icon of session objects */
	int img,selimg;
	HTREEITEM hitem=m_sessionTree.GetRootItem();
	if (!hitem) KillTimer(0);
	for (;hitem;hitem=m_sessionTree.GetNextSiblingItem(hitem))
	{
		if (m_sessionTree.ItemHasChildren(hitem)) continue;
		m_sessionTree.GetItemImage(hitem,img,selimg);
		img=(img+1)%6;
		m_sessionTree.SetItemImage(hitem,img,img);
	}
	CDialog::OnTimer(nIDEvent);
}

void CLeftPane::OnDeleteitemSessiontree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	int img,selimg;
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	m_sessionTree.GetItemImage(pNMTreeView->itemOld.hItem,img,selimg);
	*pResult = 0;
	switch (img)
	{
	/*
	If the item is a session pane : destroy the session pane only if session is not active.
	*/
	case 8:
	case 11:
		((CDialog *)pNMTreeView->itemOld.lParam)->DestroyWindow();
		break;
	/*
	If the item is an error log : free the error log.
	*/
	case 7:
		delete (SctsErrorLog *)pNMTreeView->itemOld.lParam;
		break;
	/*
	If the item is a log item : free the data which is the file name/file markers.
	*/
	case 6:
	case 9:
	case 10:
		free((void *)pNMTreeView->itemOld.lParam);
		break;
	}

}

void CLeftPane::OnDeleteitemAccounttree(NMHDR* pNMHDR, LRESULT* pResult) 
{
/*	int img,selimg;
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	m_accountTree.GetItemImage(pNMTreeView->itemOld.hItem,img,selimg);
	if (img==NODE_MSGIN || img==NODE_MSGOUT || img==NODE_LOG)
		free((void *)pNMTreeView->itemOld.lParam);*/
	*pResult = 0;
}

void CLeftPane::OnNotifySendnotification() 
{
	SctsDMServerDevice *device=(SctsDMServerDevice *)m_accountTree.GetItemData(m_accountTree.GetSelectedItem());		
	SctsDMNode *child,*node=device->FindDMNode(device->dmAccPath);
	SCTSASSERT(node);
	if (!node)
	{
		MessageBox("No DM Accounts present on device.","Notification Session",MB_ICONEXCLAMATION);
		return;
	}
	node=node->child;
	while (node)
	{
		child=device->FindDMNode("ServerID",node);
		if (child && child->data && !sctsStrcmp((char *)child->data,"Scts")) break;
		node=node->next;
	}
	if (!node)
	{
		MessageBox("No DM Accounts present on device with Scts as the ServerId.","Notification Session",MB_ICONEXCLAMATION);
		return;
	}

	CString _address;
	char *address;
	char *port;
	CNotifyAddress addressInput(_address);
	addressInput.DoModal();
	if (_address=="") return;
	address=strdup(_address);
	port=strchr(address,':');
	if (port) *port=0;

	HOSTENT *hostent=gethostbyname(address);
	if (!hostent || !hostent->h_addr_list)
	{
		MessageBox("Could not resolve address.","Notification Session",MB_ICONEXCLAMATION);
		return;
	}
	SctsDMNotification *notify=new SctsDMNotification((struct in_addr *)hostent->h_addr_list[0],port?atoi(port+1):80,device,node);
	sctsFree(address);
	notify->Create();
}

void CLeftPane::OnNotifyMakenotifiable() 
{
	SctsDMClientDevice::setNotificationDeviceParams((SctsDMClientDevice *)m_accountTree.GetItemData(m_accountTree.GetSelectedItem()),0);		
}
