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

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.

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

// ConRefPane.cpp : implementation file
//

#include "stdafx.h"
#include "scts3devman.h"
#include "ConRefPane.h"

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

/////////////////////////////////////////////////////////////////////////////
// CConRefPane dialog


CConRefPane::CConRefPane(char *_serverID,SctsDMTree *_tree,CWnd* pParent /*=NULL*/)
	: CDialog(CConRefPane::IDD, pParent),tree(_tree),update(false), currentItem(-1), serverID(_serverID)
{
    if (!tree->IsServerTree())
    {
        cliDev = (SctsDMClientDevice *)tree;
        unkDev = (SctsDMDevice *)cliDev;
    }
    else
    {
        srvDev = (SctsDMServerDevice *)tree;
        unkDev = (SctsDMServerDevice *)srvDev;
    }
    dmAccPath = unkDev->dmAccPath;
	//{{AFX_DATA_INIT(CConRefPane)
	m_napAddrType = -1;
	m_napAddr = _T("");
	m_napBearer = -1;
	m_napPassword = _T("");
	m_napUser = _T("");
	m_pxAddr = _T("");
	m_pxAddrType = -1;
	m_pxPort = _T("");
	m_pxPassword = _T("");
	m_pxUser = _T("");
	m_name = _T("");
	//}}AFX_DATA_INIT
}


void CConRefPane::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CConRefPane)
	DDX_Control(pDX, IDC_CONREFLIST, m_list);
	DDX_CBIndex(pDX, IDC_CONNAPADDRTYPE, m_napAddrType);
	DDX_Text(pDX, IDC_CONNAPADDR, m_napAddr);
	DDX_CBIndex(pDX, IDC_CONNAPBEARER, m_napBearer);
	DDX_Text(pDX, IDC_CONNAPPW, m_napPassword);
	DDX_Text(pDX, IDC_CONNAPUSER, m_napUser);
	DDX_Text(pDX, IDC_CONPXADDR, m_pxAddr);
	DDX_CBIndex(pDX, IDC_CONPXADDRTYPE, m_pxAddrType);
	DDX_Text(pDX, IDC_CONPXPNBR, m_pxPort);
	DDX_Text(pDX, IDC_CONPXPW, m_pxPassword);
	DDX_Text(pDX, IDC_CONPXUSER, m_pxUser);
	DDX_Text(pDX, IDC_CONREFNAME, m_name);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CConRefPane, CDialog)
	//{{AFX_MSG_MAP(CConRefPane)
	ON_BN_CLICKED(IDC_CONREFDISCARD, OnConrefdiscard)
	ON_EN_CHANGE(IDC_CONNAPADDR, OnUpdate)
	ON_BN_CLICKED(IDC_CONREFAPPLY, OnConrefapply)
	ON_NOTIFY(LVN_ITEMCHANGING, IDC_CONREFLIST, OnItemchangingConreflist)
	ON_CBN_SELCHANGE(IDC_CONNAPBEARER, OnUpdate)
	ON_CBN_SELCHANGE(IDC_CONNAPADDRTYPE, OnUpdate)
	ON_EN_CHANGE(IDC_CONNAPPW, OnUpdate)
	ON_EN_CHANGE(IDC_CONNAPUSER, OnUpdate)
	ON_EN_CHANGE(IDC_CONPXADDR, OnUpdate)
	ON_CBN_SELCHANGE(IDC_CONPXADDRTYPE, OnUpdate)
	ON_EN_CHANGE(IDC_CONPXPNBR, OnUpdate)
	ON_EN_CHANGE(IDC_CONPXPW, OnUpdate)
	ON_EN_CHANGE(IDC_CONPXUSER, OnUpdate)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CConRefPane message handlers

BOOL CConRefPane::OnInitDialog() 
{
	CDialog::OnInitDialog();
	SctsDMNode *node=tree->FindDMNode(dmAccPath);
	SCTSASSERT(node);
	node=tree->FindDMNode("Con", node);
	SCTSASSERT(node);
	node=node->child;
	for (;node;node=node->next)
	{
		m_list.InsertItem(0,node->name);
		m_list.SetItemData(0,(DWORD)node);
	}
	Enable(FALSE);
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CConRefPane::Refresh(SctsDMNode *acc)
{
	SctsDMNode *node,*pnode;
	m_name=acc->name;
	pnode=tree->FindDMNode("NAP",acc);
	node=tree->FindDMNode("Bearer",pnode);
	m_napBearer=atoi((char *)node->data)-1;
	node=tree->FindDMNode("AddrType",pnode);
	m_napAddrType=atoi((char *)node->data)-1;
	node=tree->FindDMNode("Addr",pnode);
	m_napAddr=(char *)node->data;
	pnode=tree->FindDMNode("Auth",pnode);
	if (pnode && (pnode=pnode->child))
	{
		node=tree->FindDMNode("Id",pnode);
		m_napUser=(char *)node->data;
		node=tree->FindDMNode("Secret",pnode);
		m_napPassword=(char *)node->data;
	}
	else
	{
		m_napUser="";
		m_napPassword="";
	}
	pnode=tree->FindDMNode("PX",acc);
	if (pnode)
	{
		node=tree->FindDMNode("PortNbr",pnode);
		if (node && node->data) m_pxPort=(char *)node->data;
		node=tree->FindDMNode("Addr",pnode);
		m_pxAddr=(char *)node->data;
		node=tree->FindDMNode("AddrType",pnode);
		m_pxAddrType=atoi((char *)node->data)-1;
		pnode=tree->FindDMNode("Auth",pnode);
		if (pnode && (pnode=pnode->child))
		{
			node=tree->FindDMNode("Id",pnode);
			m_pxUser=(char *)node->data;
			node=tree->FindDMNode("Secret",pnode);
			m_pxPassword=(char *)node->data;
		}
	}
	else
	{
		m_pxPort="";
		m_pxUser="";
		m_pxPassword="";
	}
	UpdateData(FALSE);
}

void CConRefPane::UpdateNode(char *nodeName,CString *nodeValue,bool isNonce)
{
	SctsDMNode *node=tree->FindDMNode(nodeName);
	SctsDMCommand *pCmd;
	SctsDMCommand **ppCmd=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)
	{
		/* Check if the node was modified */
		if (data && node->data && (dataSize==node->size) && !sctsMemcmp(data,node->data,dataSize)) return;
		tree->ReplaceDMNodeData(node,tree->IsServerTree()?(char *)(LPCTSTR)serverID:SIDX,data,dataSize,isNonce?"bin":0,0,ppCmd);
	}
	else
		tree->AddDMNode(nodeName,tree->IsServerTree()?(char *)(LPCTSTR)serverID:SIDX,data?(isNonce?"bin":0):"node",false,data,0,dataSize,0,ppCmd);
}

void CConRefPane::OnUpdate() 
{
	if (update) return;
	update=true;
	GetDlgItem(IDC_CONREFAPPLY)->SetWindowText("&Apply Changes");
	GetDlgItem(IDC_CONREFDISCARD)->SetWindowText("&Discard Changes");
}

void CConRefPane::Enable(BOOL enable)
{
	GetDlgItem(IDC_CONNAPBEARER)->EnableWindow(enable);
	GetDlgItem(IDC_CONNAPADDR)->EnableWindow(enable);
	GetDlgItem(IDC_CONNAPADDRTYPE)->EnableWindow(enable);
	GetDlgItem(IDC_CONNAPUSER)->EnableWindow(enable);
	GetDlgItem(IDC_CONNAPPW)->EnableWindow(enable);
	GetDlgItem(IDC_CONPXPNBR)->EnableWindow(enable);
	GetDlgItem(IDC_CONPXADDR)->EnableWindow(enable);
	GetDlgItem(IDC_CONPXADDRTYPE)->EnableWindow(enable);
	GetDlgItem(IDC_CONPXUSER)->EnableWindow(enable);
	GetDlgItem(IDC_CONPXPW)->EnableWindow(enable);
}

void CConRefPane::OnConrefdiscard() 
{
	m_napAddrType = 0;
	m_napAddr = "";
	m_napBearer = 0;
	m_napPassword = "";
	m_napUser = "";
	m_pxAddr = "";
	m_pxAddrType = 0;
	m_pxPort = "";
	m_pxPassword = "";
	m_pxUser = "";
	m_name = "";
	UpdateData(FALSE);
	Enable(FALSE);
	if (currentItem==-1) GetDlgItem(IDC_CONREFNAME)->EnableWindow(FALSE);
	if (update)
	{
		update=false;
		GetDlgItem(IDC_CONREFAPPLY)->SetWindowText("&Add");
		GetDlgItem(IDC_CONREFDISCARD)->SetWindowText("&Delete");
	}
	else if (currentItem!=-1)
	{
		SctsDMCommand *pCmd;
		SctsDMCommand **ppCmd=tree->IsServerTree()?&pCmd:0;
		tree->DeleteDMNode((SctsDMNode *)m_list.GetItemData(currentItem),SIDX,ppCmd);
		m_list.DeleteItem(currentItem);
	}
}

void CConRefPane::OnConrefapply() 
{
	int i;
	char tempBuffer[300];
	char *temp;
	char buffer[20];
	SctsDMNode *node;
	SctsDMCommand *pCmd;
	SctsDMCommand **ppCmd=tree->IsServerTree()?&pCmd:0;

	Enable(TRUE);
	if (!update)
	{
		if (currentItem!=-1) 
			m_list.SetItemState(currentItem,0,LVIS_SELECTED);
		else
			currentItem=-1;
		Enable(TRUE);
		m_napAddrType = 0;
		m_napAddr = "";
		m_napBearer = 0;
		m_napPassword = "";
		m_napUser = "";
		m_pxAddr = "";
		m_pxAddrType = 0;
		m_pxPort = "";
		m_pxPassword = "";
		m_pxUser = "";
		m_name = "";
		UpdateData(FALSE);
		GetDlgItem(IDC_CONREFAPPLY)->SetWindowText("&Apply Changes");
		GetDlgItem(IDC_CONREFDISCARD)->SetWindowText("&Discard Changes");
		GetDlgItem(IDC_CONREFNAME)->EnableWindow(TRUE);
		GetDlgItem(IDC_CONREFNAME)->SetFocus();
		update=true;
		return;
	}
	UpdateData(TRUE);
	if (currentItem==-1)
	{
		/* Check name */
		if (m_name.IsEmpty())
		{
			MessageBox("Name must have a value.","Connection",MB_ICONERROR);
			GetDlgItem(IDC_CONREFNAME)->SetFocus();
			return;
		}
		/* Check if name is unique */
		i=m_list.GetItemCount();
		while (i-- && m_list.GetItemText(i,0)!=m_name);
		if (i!=-1)
		{
			MessageBox("Connection with same name already exists.","Connection",MB_ICONERROR);
			GetDlgItem(IDC_CONREFNAME)->SetFocus();
			return;
		}
	}

	/* Check address */
	if (m_napAddr.IsEmpty())
	{
		MessageBox("NAP Address must have a value.","Connection",MB_ICONERROR);
		GetDlgItem(IDC_CONNAPADDR)->SetFocus();
		return;
	}

	sprintf(tempBuffer,"%s/Con/%s",dmAccPath,(char *)(LPCTSTR)m_name);
	temp=tempBuffer+strlen(tempBuffer);

	if (currentItem==-1)
	{
		/* Add the new DM Account */
		UpdateNode(tempBuffer,0);
		/* Add NAP */
		strcpy(temp,"/NAP");
		UpdateNode(tempBuffer,0);
	}
	
	strcpy(temp,"/NAP");
	temp=tempBuffer+strlen(tempBuffer);
	
	strcpy(temp,"/Bearer");
	UpdateNode(tempBuffer,&CString(itoa(m_napBearer+1,buffer,10)));

	strcpy(temp,"/Addr");
	UpdateNode(tempBuffer,&m_napAddr);

	strcpy(temp,"/AddrType");
    char addrTypeStr = '1' + m_napAddrType;
	UpdateNode(tempBuffer,&CString(addrTypeStr));

	strcpy(temp,"/Auth");
	node=tree->FindDMNode(tempBuffer);

	if (!m_napUser.IsEmpty() && !m_napPassword.IsEmpty())
	{
		if (!node) UpdateNode(tempBuffer,0);
		strcat(temp,"/PAP");
		temp=tempBuffer+strlen(tempBuffer);
		node=tree->FindDMNode(tempBuffer);
		if (!node) UpdateNode(tempBuffer,0);
		strcpy(temp,"/Id");
		UpdateNode(tempBuffer,&m_napUser);
		strcpy(temp,"/Secret");
		UpdateNode(tempBuffer,&m_napPassword);
	}
	else if (node) tree->DeleteDMNode(node,(char *)(LPCTSTR)serverID,ppCmd);

	sprintf(tempBuffer,"%s/Con/%s/PX",dmAccPath,(char *)(LPCTSTR)m_name);
	temp=tempBuffer+strlen(tempBuffer);
	node=tree->FindDMNode(tempBuffer);
	
	if (!m_pxAddr.IsEmpty())
	{
		if (!node) UpdateNode(tempBuffer,0);

		if (!m_pxPort.IsEmpty())
		{
			strcpy(temp,"/PortNbr");
			UpdateNode(tempBuffer,&m_pxPort);
		}

		strcpy(temp,"/Addr");
		UpdateNode(tempBuffer,&m_pxAddr);

		strcpy(temp,"/AddrType");
        char addrTypeStr = '1'+m_pxAddrType;
		UpdateNode(tempBuffer,&CString(addrTypeStr));
	
		strcpy(temp,"/Auth");
		node=tree->FindDMNode(tempBuffer);

		if (!m_pxUser.IsEmpty() && !m_pxPassword.IsEmpty())
		{
			if (!node) UpdateNode(tempBuffer,0);
			strcat(temp,"/PAP");
			temp=tempBuffer+strlen(tempBuffer);
			node=tree->FindDMNode(tempBuffer);
			if (!node) UpdateNode(tempBuffer,0);
			strcpy(temp,"/Id");
			UpdateNode(tempBuffer,&m_pxUser);
			strcpy(temp,"/Secret");
			UpdateNode(tempBuffer,&m_pxPassword);
		}
		else if (node) tree->DeleteDMNode(node,(char *)(LPCTSTR)serverID,ppCmd);
	}
	else if (node) tree->DeleteDMNode(node,(char *)(LPCTSTR)serverID,ppCmd);

	if (currentItem==-1)
	{
		*temp=0;
		m_list.InsertItem(0,m_name);
		sprintf(tempBuffer,"%s/Con/%s",dmAccPath,(char *)(LPCTSTR)m_name);
		m_list.SetItemData(0,(DWORD)tree->FindDMNode(tempBuffer));
		m_list.SetItemState(0,LVIS_SELECTED,LVIS_SELECTED);
		GetDlgItem(IDC_CONREFNAME)->EnableWindow(FALSE);
	}
	GetDlgItem(IDC_CONREFAPPLY)->SetWindowText("&Add");
	GetDlgItem(IDC_CONREFDISCARD)->SetWindowText("&Delete");
	update=false;
}



void CConRefPane::OnItemchangingConreflist(NMHDR* pNMHDR, LRESULT* pResult) 
{
	NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
	if (update) OnConrefdiscard();
	if (!(pNMListView->uNewState & LVIS_SELECTED)) 
	{
		Enable(FALSE);
		currentItem=-1;
	}
	else
	{
		Enable(TRUE);
		currentItem=pNMListView->iItem;
		Refresh((SctsDMNode *)pNMListView->lParam);
	}
	*pResult = 0;
}

BOOL CConRefPane::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);
}
