// WiFiDirectDlg.cpp : implementation file
//

#include "stdafx.h"
#include "WiFiDirect.h"
#include "WiFiDirectDlg.h"
#include "InputDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CWiFiDirectDlg dialog




CWiFiDirectDlg::CWiFiDirectDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CWiFiDirectDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CWiFiDirectDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO1, cbDiscoverability);
	DDX_Control(pDX, IDC_COMBO2, cbPairingProcedure);
	DDX_Control(pDX, IDC_CHECK1, cbAutonomousGroupOwner);
	DDX_Control(pDX, IDC_EDIT1, edGroupOwnerIntent);
	DDX_Control(pDX, IDC_CHECK2, cbDisplayPin);
	DDX_Control(pDX, IDC_CHECK3, cbProvidePin);
	DDX_Control(pDX, IDC_CHECK4, cbPushButton);
	DDX_Control(pDX, IDC_LIST1, lvDevices);
	DDX_Control(pDX, IDC_LIST2, lbLog);
}

BEGIN_MESSAGE_MAP(CWiFiDirectDlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_BUTTON4, &CWiFiDirectDlg::OnBnClickedButton4)
	ON_BN_CLICKED(IDC_BUTTON3, &CWiFiDirectDlg::OnBnClickedButton3)
	ON_BN_CLICKED(IDC_BUTTON1, &CWiFiDirectDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CWiFiDirectDlg::OnBnClickedButton2)
END_MESSAGE_MAP()


// CWiFiDirectDlg message handlers

BOOL CWiFiDirectDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	cbDiscoverability.AddString(_T("Intensive"));
	cbDiscoverability.AddString(_T("None"));
	cbDiscoverability.AddString(_T("Normal"));
	cbDiscoverability.SetCurSel(2);

	cbPairingProcedure.AddString(_T("ppInvitation"));
	cbPairingProcedure.AddString(_T("ppGroupOwnerNegotiation"));
	cbPairingProcedure.SetCurSel(1);

	edGroupOwnerIntent.SetWindowText(_T("14"));

	cbPushButton.SetCheck(TRUE);

	lvDevices.InsertColumn(0, _T("Device name"), 0, 135);
	lvDevices.InsertColumn(1, _T("Id"), 0, 135);
	lvDevices.InsertColumn(2, _T("Status"), 0, 80);
	lvDevices.SetExtendedStyle(lvDevices.GetExtendedStyle() | LVS_EX_FULLROWSELECT);

	__hook(&CwclWiFiDirectAdvertiser::OnStarted, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserStarted);
	__hook(&CwclWiFiDirectAdvertiser::OnStopped, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserStopped);
	__hook(&CwclWiFiDirectAdvertiser::OnAcceptDevice, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserAcceptDevice);
	__hook(&CwclWiFiDirectAdvertiser::OnDeviceConnected, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserDeviceConnected);
	__hook(&CwclWiFiDirectAdvertiser::OnDeviceDisconnected, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserDeviceDisconnected);
	__hook(&CwclWiFiDirectAdvertiser::OnPairCompleted, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserPairCompleted);
	__hook(&CwclWiFiDirectAdvertiser::OnPairConfirm, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserPairConfirm);
	__hook(&CwclWiFiDirectAdvertiser::OnPairDisplayPin, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserPairDisplayPin);
	__hook(&CwclWiFiDirectAdvertiser::OnPairProvidePin, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserPairProvidePin);
	__hook(&CwclWiFiDirectAdvertiser::OnPairGetParams, &wclWiFiDirectAdvertiser, &CWiFiDirectDlg::wclWiFiDirectAdvertiserPairGetParams);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CWiFiDirectDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CWiFiDirectDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CWiFiDirectDlg::OnDestroy()
{
	wclWiFiDirectAdvertiser.Stop();
	__unhook(&wclWiFiDirectAdvertiser);

	CDialog::OnDestroy();
}

void CWiFiDirectDlg::OnBnClickedButton4()
{
	lbLog.ResetContent();
}

void CWiFiDirectDlg::OnBnClickedButton3()
{
	POSITION Pos = lvDevices.GetFirstSelectedItemPosition();
	if (Pos == NULL)
		AfxMessageBox(_T("Select device"));
	else
	{
		CString s = lvDevices.GetItemText(lvDevices.GetNextSelectedItem(Pos), 1);
		for (size_t i = 0; i < wclWiFiDirectAdvertiser.Count; i++)
		{
			if (wclWiFiDirectAdvertiser.Devices[i]->Id == tstring(s))
			{
				int Res = wclWiFiDirectAdvertiser.Devices[i]->Disconnect();
				if (Res != WCL_E_SUCCESS)
				{
					s.Format(_T("Disconnect error: 0x%.8X"), Res);
					AfxMessageBox(s);
				}
				
				break;
			}
		}
	}
}

void CWiFiDirectDlg::OnBnClickedButton2()
{
	int Res = wclWiFiDirectAdvertiser.Stop();
	if (Res != WCL_E_SUCCESS)
	{
		CString s;
		s.Format(_T("Stop error: 0x%.8X"), Res);
		AfxMessageBox(s);
	}
}

void CWiFiDirectDlg::OnBnClickedButton1()
{
	if (wclWiFiDirectAdvertiser.Active)
		AfxMessageBox(_T("Already running"));
	else
	{
		switch (cbDiscoverability.GetCurSel())
		{
			case 0:
				wclWiFiDirectAdvertiser.Discoverability = adIntensive;
				break;
			case 1:
				wclWiFiDirectAdvertiser.Discoverability = adNone;
				break;
			case 2:
				wclWiFiDirectAdvertiser.Discoverability = adNormal;
				break;
		}
		wclWiFiDirectAdvertiser.AutonomousGroupOwnerEnabled = (cbAutonomousGroupOwner.GetCheck() != FALSE);
		
		int Res = wclWiFiDirectAdvertiser.Start();
		if (Res != WCL_E_SUCCESS)
		{
			CString s;
			s.Format(_T("Start error: 0x%.8X"), Res);
			AfxMessageBox(s);
		}
	}
}

int CWiFiDirectDlg::GetItem(const tstring& Id)
{
	for (int i = 0; i < lvDevices.GetItemCount(); i++)
	{
		if (lvDevices.GetItemText(i, 1) == CString(Id.c_str()))
			return i;
	}
	return -1;
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserStarted(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	lbLog.AddString(_T("Advertiser has been started"));
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserStopped(void* Sender)
{
	UNREFERENCED_PARAMETER(Sender);

	lvDevices.DeleteAllItems();
	lbLog.AddString(_T("Advertiser has been stopped"));
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserAcceptDevice(void* Sender,
	CwclWiFiDirectDevice* const Device, bool& Accept)
{
	UNREFERENCED_PARAMETER(Sender);

	tstring s = _T("Accept connection from ") + Device->Name + _T(" ?");
	Accept = (AfxMessageBox(s.c_str(), MB_YESNO | MB_APPLMODAL | MB_ICONQUESTION) == IDYES);
	if (Accept)
	{
		int i = lvDevices.GetItemCount();
		lvDevices.InsertItem(i, Device->Name.c_str());
		lvDevices.SetItemText(i, 1, Device->Id.c_str());
		lvDevices.SetItemText(i, 2, _T("Connecting"));
	}
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserDeviceConnected(void* Sender,
	CwclWiFiDirectDevice* const Device, const int Error)
{
	UNREFERENCED_PARAMETER(Sender);

	int Item = GetItem(Device->Id);
	if (Item != -1)
	{
		if (Error == WCL_E_SUCCESS)
		{
			lvDevices.SetItemText(Item, 2, _T("Connected"));
			
			lbLog.AddString(CString(Device->Name.c_str()) + _T(" connected"));
			lbLog.AddString(CString(_T("  Local IP: ")) + Device->LocalAddress.c_str());
			lbLog.AddString(CString(_T("  Remote IP: ")) + Device->RemoteAddress.c_str());
		}
		else
		{
			CString s;
			s.Format(_T(" connect error: 0x%.8X"), Error);
			lbLog.AddString(Device->Name.c_str() + s);
			lvDevices.DeleteItem(Item);
		}
	}
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserDeviceDisconnected(void* Sender,
	CwclWiFiDirectDevice* const Device, const int Reason)
{
	UNREFERENCED_PARAMETER(Sender);

	int Item = GetItem(Device->Id);
	if (Item != -1)
	{
		CString s;
		s.Format(_T(" disconnected. Reason: 0x%.8X"), Reason);
		lbLog.AddString(Device->Name.c_str() + s);
		lvDevices.DeleteItem(Item);
	}
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserPairCompleted(void* Sender,
	CwclWiFiDirectDevice* const Device, const int Result)
{
	UNREFERENCED_PARAMETER(Sender);

	CString s;
	s.Format(_T(" paired. Result: 0x%.8X"), Result);
	lbLog.AddString(Device->Name.c_str() + s);
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserPairConfirm(void* Sender,
	CwclWiFiDirectDevice* const Device, bool& Confirm)
{
	UNREFERENCED_PARAMETER(Sender);

	tstring s = _T("Confirm ") + Device->Name + _T(" connection?");
	Confirm = (AfxMessageBox(s.c_str(), MB_YESNO | MB_APPLMODAL | MB_ICONQUESTION) == IDYES);
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserPairDisplayPin(void* Sender,
	CwclWiFiDirectDevice* const Device, const tstring& Pin)
{
	UNREFERENCED_PARAMETER(Sender);

	AfxMessageBox(CString(_T("Use ")) + Pin.c_str() + CString(_T(" PIN to pair with ")) +
		Device->Name.c_str());
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserPairGetParams(void* Sender,
	CwclWiFiDirectDevice* const Device, short& GroupOwnerIntent,
	wclWiFiDirectConfigurationMethods& ConfigurationMethods,
	wclWiFiDirectPairingProcedure& PairingProcedure)
{
	UNREFERENCED_PARAMETER(Sender);

	lbLog.AddString(Device->Name.c_str() + CString(_T(" quering pairing params")));
	
	if (cbPairingProcedure.GetCurSel() == 0)
		PairingProcedure = ppInvitation;
	else
		PairingProcedure = ppGroupOwnerNegotiation;

	CString s;
	edGroupOwnerIntent.GetWindowText(s);
	GroupOwnerIntent = LOWORD(_ttoi(s));
	
	ConfigurationMethods.clear();
	if (cbDisplayPin.GetCheck())
		ConfigurationMethods.insert(cmDisplayPin);
	if (cbProvidePin.GetCheck())
		ConfigurationMethods.insert(cmProvidePin);
	if (cbPushButton.GetCheck())
		ConfigurationMethods.insert(cmPushButton);
}

void CWiFiDirectDlg::wclWiFiDirectAdvertiserPairProvidePin(void* Sender,
	CwclWiFiDirectDevice* const Device, tstring& Pin)
{
	UNREFERENCED_PARAMETER(Sender);
	UNREFERENCED_PARAMETER(Device);

	Pin = _T("");
	CInputDlg Dlg;
	if (Dlg.DoModal() == IDOK)
	{
		CString s;
		Dlg.edPin.GetWindowText(s);
		Pin = s;
	}
}
