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

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.

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

// DMAccountPane.cpp : implementation file
//

#include "stdafx.h"
#include "scts3devman.h"
#include "DMAccountPane.h"
#include "SctsDevManDMAccount.h"
//#include "UIAInput.h"

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

/////////////////////////////////////////////////////////////////////////////
// CDMAccountPane dialog


CDMAccountPane::CDMAccountPane(SctsDMTree *_tree,CWnd* pParent /*=NULL*/)
	: CDialog(CDMAccountPane::IDD, pParent),tree(_tree),update(false), currentItem(-1),
      unkDev(0), cliDev(0), srvDev(0)
{
    if (!tree->IsServerTree())
    {
        cliDev = (SctsDMClientDevice *)tree;
        unkDev = (SctsDMDevice *)cliDev;
    }
    else
    {
        srvDev = (SctsDMServerDevice *)tree;
        unkDev = (SctsDMServerDevice *)srvDev;
    }
    dmAccPath = unkDev->dmAccPath;
	//{{AFX_DATA_INIT(CDMAccountPane)
	m_cauth = 0;
	m_conref = -1;
	m_cpassword = _T("");
	m_cuser = _T("");
	m_port = _T("");
	m_sauth = 0;
	m_sid = _T("");
	m_spassword = _T("");
	m_addr = _T("");
	m_addrType = 0;
	m_name = _T("");
	//}}AFX_DATA_INIT
}


void CDMAccountPane::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDMAccountPane)
	DDX_Control(pDX, IDC_DMACCLIST, m_list);
	DDX_Radio(pDX, IDC_DMACCCAUTHNONE, m_cauth);
	DDX_CBIndex(pDX, IDC_DMACCCONREF, m_conref);
	DDX_Text(pDX, IDC_DMACCCPWD, m_cpassword);
	DDX_Text(pDX, IDC_DMACCCUSER, m_cuser);
	DDX_Text(pDX, IDC_DMACCPNBR, m_port);
	DDX_Radio(pDX, IDC_DMACCSAUTHNONE, m_sauth);
	DDX_Text(pDX, IDC_DMACCSID, m_sid);
	DDX_Text(pDX, IDC_DMACCSPWD, m_spassword);
	DDX_Text(pDX, IDC_DMACCADDR, m_addr);
	DDX_CBIndex(pDX, IDC_DMACCADDRTYPE, m_addrType);
	DDX_Text(pDX, IDC_DMACCNAME, m_name);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDMAccountPane, CDialog)
	//{{AFX_MSG_MAP(CDMAccountPane)
	ON_BN_CLICKED(IDC_DMACCAPPLY, OnDmaccapply)
	ON_EN_CHANGE(IDC_DMACCSID, OnUpdate)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_DMACCLIST, OnItemchangedDmacclist)
	ON_BN_CLICKED(IDC_DMACCDISCARD, OnDmaccdiscard)
	ON_BN_CLICKED(IDC_DMACCCONNECT, OnDmaccconnect)
	ON_EN_CHANGE(IDC_DMACCADDR, OnUpdate)
	ON_EN_CHANGE(IDC_DMACCPNBR, OnUpdate)
	ON_EN_CHANGE(IDC_DMACCSPWD, OnUpdate)
	ON_EN_CHANGE(IDC_DMACCCUSER, OnUpdate)
	ON_EN_CHANGE(IDC_DMACCCPWD, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCCAUTHNONE, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCCAUTHBASIC, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCCAUTHDIGEST, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCSAUTHNONE, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCSAUTHBASIC, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCSAUTHDIGEST, OnUpdate)
	ON_CBN_SELCHANGE(IDC_DMACCCONREF, OnUpdate)
	ON_CBN_SELCHANGE(IDC_DMACCADDRTYPE, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCSAUTHHMAC, OnUpdate)
	ON_BN_CLICKED(IDC_DMACCCAUTHHMAC, OnUpdate)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDMAccountPane message handlers

BOOL CDMAccountPane::OnInitDialog() 
{
    /*
    SctsSemaphore lock(0,1);
    CString input = "Hello World";
    CUIAInput dlg(lock,"123","456",input,'T','A',0,1);
    dlg.DoModal();
    MessageBox(input);
    */

	CDialog::OnInitDialog();
	SctsDMNode *node;

	CComboBox *conlist=(CComboBox *)GetDlgItem(IDC_DMACCCONREF);
    MDAccType& accounts = unkDev->accounts;


    MDAccType::iterator it = accounts.begin();
	for (;it!=accounts.end();++it)
	{
        //MulDynAccItem accountTemp = it->second;
        m_list.InsertItem(0,it->first.c_str());
		m_list.SetItemData(0,(DWORD)&(it->second));
	}

    node = tree->FindDMNode(dmAccPath);
    SCTSASSERT(node);
    node = tree->FindDMNode("Con", node);
	if (node)
	{
		int i=0;
		for (node=node->child;node;node=node->next)
		{
			conlist->InsertString(i,node->name);
			conlist->SetItemData(i,(DWORD)node);
			++i;
		}
	}

    Enable(FALSE);
	GetDlgItem(IDC_DMACCCONNECT)->ShowWindow(tree->IsServerTree()?SW_HIDE:SW_SHOW);
	return TRUE;  // return TRUE unless you set the focus to a control
}

void CDMAccountPane::Refresh(MulDynAccItem *dynAcc)
{
    /*
     * Change to support DM 1.2 DMAcc node. 
     */
	SctsDMNode *node;
    SctsDMNode *acc=tree->FindDMNode((char *)(dynAcc->accPath.c_str()));
    SCTSASSERT(acc);
    SctsDMNode *tmpNode[4]={0};

    m_name=dynAcc->accName.c_str();

    node=tree->FindDMNode("ServerID",acc);
	m_sid=(node && node->data)?(char *)node->data:"";

    node=tree->FindDMNode((char *)(dynAcc->subToConRef+"/ConRef").c_str(),acc);
	if (node && node->data)
	{
		int i=-1;
		SctsDMNode *conref = tree->FindDMNode(dmAccPath);
        SCTSASSERT(conref);
        conref = tree->FindDMNode("Con", conref);
		if (conref)
		{
			for (conref=conref->child;conref;conref=conref->next)
			{
				++i;
				if (!strcmp(conref->name,(char *)node->data)) break;
			}
			m_conref=i;
		}
	}

    node=tree->FindDMNode((char *)(dynAcc->subAppAddr+"/Addr").c_str(),acc);
    m_addr=(node && node->data)?(char *)node->data:"";

    m_addrType=-1;
    node=tree->FindDMNode((char *)(dynAcc->subAppAddr+"/AddrType").c_str(),acc);
    if (node && node->data)
    {
        m_addrType=0;
    }

    node=tree->FindDMNode((char *)(dynAcc->subPort+"/PortNbr").c_str(),acc);
    m_port=(node && node->data)?(char *)node->data:"";

    node=tree->FindDMNode((char *)(dynAcc->subAppAuthServer+"/AAuthSecret").c_str(),acc);
    m_spassword=(node && node->data)?(char *)node->data:"";

    node=tree->FindDMNode((char *)(dynAcc->subAppAuthClient+"/AAuthSecret").c_str(),acc);
    m_cpassword=(node && node->data)?(char *)node->data:"";

    node=tree->FindDMNode((char *)(dynAcc->subAppAuthClient+"/AAuthName").c_str(),acc);
	m_cuser=(node && node->data)?(char *)node->data:"";

    UpdateData(FALSE);
}


void CDMAccountPane::UpdateNode(char *nodeName,CString *nodeValue,bool isNonce)
{
	SctsDMNode *node=tree->FindDMNode(nodeName);
	//SctsDMCommand *pCmd;
	SctsDMCommand **ppCmd=0;//tree->IsServerTree()?((node && isNonce)?0:&pCmd):0;
	void *data=nodeValue?(isNonce?(void *)nodeValue:(void *)(LPCTSTR)(*nodeValue)):0;
	int dataSize=data?(isNonce?sizeof(void *):nodeValue->GetLength()):0;

	if (node)
	{
		/* Return if there is nothing to update */
		if (!dataSize && !node->size) return;
		/* Do not update the nonce, if the node already has data */
		if (isNonce && node->data && node->size) return;
		/* Check if the node was modified */
		if (data && node->data && (dataSize==node->size) && !sctsMemcmp(data,node->data,dataSize)) return;
		/* DMEvent V1.1.1 -- Replace on the node ServerPW and ClientPW need not 
	       send replace commands to the client as the client will not allow this */
		if (ppCmd && node->IsParent(tree->FindDMNode(dmAccPath))/* && (!sctsStrcmp(node->name,"AAuthSecret"))*/)
			ppCmd=0;
		tree->ReplaceDMNodeData(node,tree->IsServerTree()?(char *)(LPCTSTR)m_sid:SIDX,data,dataSize,isNonce?"bin":((data && node->format==DMFORMAT_NULL)?"chr":0),0,ppCmd);
	}
	else
		tree->AddDMNode(nodeName,tree->IsServerTree()?(char *)(LPCTSTR)m_sid:SIDX,data?(isNonce?"bin":0):"node",false,data,0,dataSize,0,ppCmd);
}
/*
 * Change to support DM 1.2 DMAcc node. 
 */
bool CDMAccountPane::UpdateNode(const MulDynAccItem& dynAcc)
{
    std::string nodeRootName = dynAcc.accPath;
    std::string nodeFullName;
    SctsDMNode *pNode=0;
    std::string defACL="Get=";
    defACL+=(LPCSTR)m_sid;
    if ((pNode = tree->FindDMNode((char *)nodeRootName.c_str())) == 0)
    {
        if (tree->AddDMNode((char *)nodeRootName.c_str(),SIDX,"node",false,0,0,0,&pNode,0) != 200)
        {
            return false;
        }
    }
    if (pNode->acl) sctsFree(pNode->acl);
    pNode->acl = sctsStrdup((char *)defACL.c_str());

    nodeFullName = nodeRootName +"/" + dynAcc.subToConRef;
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);

    nodeFullName = nodeRootName + "/" + dynAcc.subAppAddr;
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);

    nodeFullName = nodeRootName + "/" + dynAcc.subPort;
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);

    nodeFullName = nodeRootName + "/" + dynAcc.subAppAuthClient;
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);
    nodeFullName = nodeRootName + "/" + dynAcc.subAppAuthServer;
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);

    nodeFullName = nodeRootName + "/Ext";
    tree->AddFullDMNode((char *)nodeFullName.c_str(),SIDX,"node",false,0,0,0,0,0);

    nodeFullName = nodeRootName + "/AppID";
    UpdateNode((char *)nodeFullName.c_str(),&CString("w7"),false);

    nodeFullName = nodeRootName + "/" + dynAcc.subAppAuthClient + "/AAuthLevel";
    UpdateNode((char *)nodeFullName.c_str(),&CString("CLCRED"),false);
    nodeFullName = nodeRootName + "/" + dynAcc.subAppAuthServer + "/AAuthLevel";
    UpdateNode((char *)nodeFullName.c_str(),&CString("SRVCRED"),false);

    return true;
}

void CDMAccountPane::OnDmaccapply() 
{
	int i;
	char *path;
	CComboBox *conlist=(CComboBox *)GetDlgItem(IDC_DMACCCONREF);
	SctsDMNode *node;
	
	Enable(TRUE);
	if (!update)
	{
		if (currentItem!=-1) 
			m_list.SetItemState(currentItem,0,LVIS_SELECTED);
		else
			currentItem=-1;
		Enable(TRUE);
		m_cauth = 0;
		m_conref = -1;
		m_cpassword = "";
		m_cuser = "";
		m_port = "";
		m_sauth = 0;
		m_sid = "";
		m_spassword = "";
		m_addr = "";
		m_addrType = 0;
		m_name = "";
		UpdateData(FALSE);
		if (!tree->IsServerTree()) GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(FALSE);
		GetDlgItem(IDC_DMACCAPPLY)->SetWindowText("&Apply Changes");
		GetDlgItem(IDC_DMACCDISCARD)->SetWindowText("&Discard Changes");
		GetDlgItem(IDC_DMACCNAME)->EnableWindow(TRUE);
		GetDlgItem(IDC_DMACCNAME)->SetFocus();
		update=true;
		currentItem=-1;
		return;
	}
	UpdateData(TRUE);

	if (currentItem==-1)
	{
		/* Check name */
		if (m_name.IsEmpty())
		{
			MessageBox("Name must have a value.","DM Account",MB_ICONERROR);
			GetDlgItem(IDC_DMACCNAME)->SetFocus();
			return;
		}
		/* Check if name is unique */
		i=m_list.GetItemCount();
		while (i-- && m_list.GetItemText(i,0)!=m_name);
		if (i!=-1)
		{
			MessageBox("Account with same name already exists.","DM Account",MB_ICONERROR);
			GetDlgItem(IDC_DMACCNAME)->SetFocus();
			return;
		}
	}

	/* Check server ID */
	if (m_sid.IsEmpty())
	{
		MessageBox("Server ID must have a value.","DM Account",MB_ICONERROR);
		GetDlgItem(IDC_DMACCSID)->SetFocus();
		return;
	}
	/* Check if server ID is unique */
	for (i=m_list.GetItemCount();i--;)
	{
		if (i==currentItem) continue;
        MulDynAccItem *dynAcc = (MulDynAccItem *)m_list.GetItemData(i);
        node=tree->FindDMNode((char *)(dynAcc->accPath + "ServerID").c_str());
		if (node && node->data && !strcmp((char *)node->data,(LPCTSTR)m_sid))
		{
			MessageBox("Server ID must be unique.","DM Account",MB_ICONERROR);
			GetDlgItem(IDC_DMACCSID)->SetFocus();
			return;
		}
	}
	/* Check address */
	if (m_addr.IsEmpty())
	{
		MessageBox("Address must have a value.","DM Account",MB_ICONERROR);
		GetDlgItem(IDC_DMACCADDR)->SetFocus();
		return;
	}

	/* Check address format */
	if (!m_addrType)
	{
		SctsURI uri((char *)(LPCTSTR)m_addr);
		if (!uri.scheme || !uri.authority || !uri.path)
		{
			MessageBox("Invalid HTTP address. Address must be of the form : scheme://authority/path.","DM Account");
			GetDlgItem(IDC_DMACCADDR)->SetFocus();
			return;
		}
	}
		
	/* Check server password */
	if (m_sauth && m_spassword.IsEmpty())
	{
		MessageBox("Server password must have a value.","DM Account",MB_ICONERROR);
		GetDlgItem(IDC_DMACCSPWD)->SetFocus();
		return;
	}

	/* Check client username and password */
	if (m_cauth && m_cuser.IsEmpty())
	{
		MessageBox("Client user name must have a value.","DM Account",MB_ICONERROR);
		GetDlgItem(IDC_DMACCCUSER)->SetFocus();
		return;
	}
	if (m_cauth && m_cpassword.IsEmpty())
	{
		MessageBox("Client password must have a value.","DM Account",MB_ICONERROR);
		GetDlgItem(IDC_DMACCCPWD)->SetFocus();
		return;
	}

    MDAccType::iterator it = unkDev->accounts.find((LPCTSTR)m_name);
    MulDynAccItem account;
    if (it != unkDev->accounts.end())
    {
        account = it->second;
    }
    else
    {
        account.accName = (LPCSTR)m_name;
        account.accPath = (std::string)dmAccPath + "/" + (LPCSTR)m_name;
        account.subAppAddr = (std::string)"AppAddr/" + (LPCSTR)m_sid;
        account.subPort = account.subAppAddr + "/Port/" + (LPCSTR)m_sid;
        account.subAppAuthClient = (std::string)"AppAuth/" + (LPCSTR)m_sid + "Client";
        account.subAppAuthServer = (std::string)"AppAuth/" + (LPCSTR)m_sid + "Server";
        account.subToConRef = (std::string)"ToConRef/" + (LPCSTR)m_sid;
    }

	if (currentItem==-1)
	{
		/*
		DMEvent V1.1.1 -- Removed Atomic ,as Atomic is optional 
		
		  Add the new DM Account within atomic if it is a server device 
		if (tree->IsServerTree()) ((SctsDMServerTree *)tree)->InsertCommand(new SctsDMCommand(SCTS_ATOMIC_START)); */
		if (!UpdateNode(account))
        {
            MessageBox("Add account failed.","DM Account",MB_ICONERROR);
            OnDmaccdiscard();
            return;
        }
	}

    /*
     * Change to support DM 1.2 DMAcc node. 
     */
	UpdateData(FALSE);
	node=0;
	if (m_conref>-1) node=(SctsDMNode *)conlist->GetItemData(m_conref);
	path=node?sctsStrdup(node->name):sctsStrdup("");
	UpdateNode((char *)(account.accPath + "/" + account.subToConRef + "/ConRef").c_str(), &CString(path));
	sctsFree(path);

    UpdateNode((char *)(account.accPath + "/ServerID").c_str(), &m_sid);

	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthClient + "/AAuthName").c_str(),&m_cuser);

	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthServer + "/AAuthName").c_str(),&m_name);

    UpdateNode((char *)(account.accPath + "/" + account.subAppAuthClient + "/AAuthSecret").c_str(),&m_cpassword);

	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthServer + "/AAuthSecret").c_str(),&m_spassword);

	UpdateNode((char *)(account.accPath + "/" + account.subAppAddr + "/Addr").c_str(),&m_addr);
    
    switch (m_addrType+1)
    {
        case 1:
        case 2:
        case 3:
        default:
	        UpdateNode((char *)(account.accPath + "/" + account.subAppAddr + "/AddrType").c_str(),&CString("URI"));
            break;
    }

	UpdateNode((char *)(account.accPath + "/" + account.subPort + "/PortNbr").c_str(),&m_port);

    CString CAuthLevel,SAuthLevel;
    switch (m_cauth)
    {
    case 1:
        CAuthLevel="BASIC";
        break;
    case 2:
        CAuthLevel="DIGEST";
        break;
    case 3:
        CAuthLevel="HMAC";
        break;
    }
    switch (m_sauth)
    {
    case 1:
        SAuthLevel="BASIC";
        break;
    case 2:
        SAuthLevel="DIGEST";
        break;
    case 3:
        SAuthLevel="HMAC";
        break;
    }
	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthClient + "/AAuthType").c_str(),&CAuthLevel);
	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthServer + "/AAuthType").c_str(),&SAuthLevel);

    UpdateNode((char *)(account.accPath + "/" + account.subAppAuthClient + "/AAuthData").c_str(),(m_cauth>=2)?(CString *)&m_cauth:&CString(""),true);
	UpdateNode((char *)(account.accPath + "/" + account.subAppAuthServer + "/AAuthData").c_str(),(m_sauth==2)?(CString *)&m_sauth:&CString(""),true);

	if (!tree->IsServerTree()) 
	{
		cliDev->accountNode = tree->FindDMNode((char *)(account.accPath.c_str()));
		cliDev->SetAuthType(false,(SctsAuthType)m_cauth);
		cliDev->SetAuthType(true,(SctsAuthType)m_sauth);
		GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(TRUE);
	}
	if (currentItem==-1)
	{
		m_list.InsertItem(0,m_name);
        unkDev->accounts[(LPCSTR)m_name] = account;
		m_list.SetItemData(0,(DWORD)&(unkDev->accounts[(LPCSTR)m_name]));
		m_list.SetItemState(0,LVIS_SELECTED,LVIS_SELECTED);
		GetDlgItem(IDC_DMACCNAME)->EnableWindow(FALSE);
		/*
		DMEvent V1.1.1 Removed Atomic as it is optional 
		  Close the atomic tag if it is a server device 
		if (tree->IsServerTree()) ((SctsDMServerTree *)tree)->InsertCommand(new SctsDMCommand(SCTS_ATOMIC_END)); */
	}

    GetDlgItem(IDC_DMACCAPPLY)->SetWindowText("&Add");
	GetDlgItem(IDC_DMACCDISCARD)->SetWindowText("&Delete");
	update=false;
}

void CDMAccountPane::OnUpdate() 
{
	if (update) return;
	update=true;
	if (!tree->IsServerTree()) GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(FALSE);
	GetDlgItem(IDC_DMACCAPPLY)->SetWindowText("&Apply Changes");
	GetDlgItem(IDC_DMACCDISCARD)->SetWindowText("&Discard Changes");
}

void CDMAccountPane::Enable(BOOL enable)
{
	GetDlgItem(IDC_DMACCSID)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCCONREF)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCADDR)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCADDRTYPE)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCPNBR)->EnableWindow(enable);
	if (!tree->IsServerTree())
	{
		GetDlgItem(IDC_DMACCSAUTHNONE)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCSAUTHBASIC)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCSAUTHDIGEST)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCSAUTHHMAC)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCCAUTHNONE)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCCAUTHBASIC)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCCAUTHDIGEST)->EnableWindow(enable);
		GetDlgItem(IDC_DMACCCAUTHHMAC)->EnableWindow(enable);
	}
	GetDlgItem(IDC_DMACCCPWD)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCSPWD)->EnableWindow(enable);
	GetDlgItem(IDC_DMACCCUSER)->EnableWindow(enable);
}

void CDMAccountPane::OnItemchangedDmacclist(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	if (update) OnDmaccdiscard();
	if (!(pNMListView->uNewState & LVIS_SELECTED)) 
	{
		Enable(FALSE);
		currentItem=-1;
		if (!tree->IsServerTree()) GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(FALSE);
	}
	else
	{
		Enable(TRUE);
		currentItem=pNMListView->iItem;
		if (currentItem!=-1) 
		{
            Refresh((MulDynAccItem *)pNMListView->lParam);
			if (!tree->IsServerTree()) 
			{
				GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(TRUE);
                MulDynAccItem *dynAcc = (MulDynAccItem *)m_list.GetItemData(currentItem);
				cliDev->accountNode=tree->FindDMNode((char *)(dynAcc->accPath.c_str()));
				m_cauth=cliDev->GetAuthType(false);
				m_sauth=cliDev->GetAuthType(true);
				UpdateData(FALSE);
			}
		}
	}
	*pResult = 0;
}

void CDMAccountPane::OnDmaccdiscard() 
{
	m_cauth = 0;
	m_conref = -1;
	m_cpassword = "";
	m_cuser = "";
	m_port = "";
	m_sauth = 0;
	m_sid = "";
	m_spassword = "";
	m_addr = "";
	m_addrType = 0;
	m_name = "";
	UpdateData(FALSE);
	Enable(FALSE);
	if (currentItem==-1) GetDlgItem(IDC_DMACCNAME)->EnableWindow(FALSE);
	if (update)
	{
		update=false;
		if (!tree->IsServerTree()) GetDlgItem(IDC_DMACCCONNECT)->EnableWindow(TRUE);
		GetDlgItem(IDC_DMACCAPPLY)->SetWindowText("&Add");
		GetDlgItem(IDC_DMACCDISCARD)->SetWindowText("&Delete");
		if (currentItem!=-1) Refresh((MulDynAccItem *)m_list.GetItemData(currentItem));
		
	}
	else if (currentItem!=-1)
	{
		int rc;
		//SctsDMCommand *pCmd;
		SctsDMCommand **ppCmd=0;//tree->IsServerTree()?&pCmd:0;
		SctsDMNode *node;
		char *sid=0;
        MulDynAccItem *dynAcc = (MulDynAccItem *)m_list.GetItemData(currentItem);
		node=tree->FindDMNode((char *)(dynAcc->accPath + "ServerID").c_str());
		if (node && node->data) sid=sctsStrdup((char *)node->data);
        node=tree->FindDMNode((char *)(dynAcc->accPath.c_str()));
		if ((rc=tree->DeleteDMNode(node,SIDX,ppCmd))==200 && !tree->IsServerTree() && sid)
			tree->RemoveServerID(sid);	
        unkDev->accounts.erase(dynAcc->accName);
		m_list.DeleteItem(currentItem);
	}
}

void CDMAccountPane::OnDmaccconnect() 
{
	SctsDMClientDevice *device=(SctsDMClientDevice *)tree;
	SctsDMNode *node;
	node=device->FindDMNode("ServerID",device->accountNode);
	SCTSASSERT(node && node->data);
	device->serverID=sctsStrdup((char *)node->data);
	
	SctsDMClientSession *clientSession=new SctsDMClientSession(device,device->encoding);
	clientSession->Create();	 
}

BOOL CDMAccountPane::PreTranslateMessage(MSG* pMsg) 
{
	/* Disable ESC  and Enter */
	if (pMsg->message==WM_KEYDOWN && (pMsg->wParam==VK_ESCAPE || pMsg->wParam==VK_RETURN)) return TRUE;
	
	return CDialog::PreTranslateMessage(pMsg);
}
