// CppSampleDlg.cpp : implementation file
//

#include "stdafx.h"
#include "CppSample.h"
#include "CppSampleDlg.h"
#include "VRAPI.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CCppSampleDlg dialog
CCppSampleDlg *g_pMainDlg = 0;

int VR_CALLBACK cb_call_offered(int ChanIndex, const char* CallerIP, const char* CallerID, const char* CalleeIP, const char* CalleeID, unsigned int CallTime, const char* UniqueID, const char* AudioFile, int CallDir)
{
	if(g_pMainDlg)
		g_pMainDlg->OnCallOffered(ChanIndex, CallerIP, CallerID, CalleeIP, CalleeID, CallTime, UniqueID, AudioFile);

	return 1;
}

void VR_CALLBACK cb_call_connected(int ChanIndex, const char* CallerIP, const char* CallerID, const char* CalleeIP, const char* CalleeID, unsigned int InitTime, unsigned int ConnectTime, const char* UniqueID, const char* AudioFile, int CallDir)
{
	if(g_pMainDlg)
		g_pMainDlg->OnCallConnected(ChanIndex, CallerIP, CallerID, CalleeIP, CalleeID, InitTime, ConnectTime, UniqueID, AudioFile);
}

void VR_CALLBACK cb_call_idle(int ChanIndex, const char* CallerIP, const char* CallerID, const char* CalleeIP, const char* CalleeID, unsigned int InitTime, unsigned int ConnectTime, unsigned int EndTime, const char* UniqueID, const char* AudioFile, int AudioFileNum, int Reason, int CallDir, const char* sDTMF, int Codec)
{
	if(g_pMainDlg)
		g_pMainDlg->OnCallEnd(ChanIndex, CallerIP, CallerID, CalleeIP, CalleeID, InitTime, ConnectTime, EndTime, UniqueID, AudioFile, AudioFileNum, Reason, CallDir, sDTMF, Codec);
}

void VR_CALLBACK cb_call_audio_buffer(int ChanIndex, const char* UniqueID, int Direction, const char* Buff, int BuffSize)
{
	if(g_pMainDlg)
		g_pMainDlg->OnCallAudioStream(ChanIndex, UniqueID, Direction, (unsigned char*)Buff, BuffSize);
}


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

	Capturing = false;

/*
	for(int i=0; i<MAX_CHAN_NUM; i++)
	{
		fpAudio[i][0] = NULL;
		fpAudio[i][1] = NULL;
	}
*/

	g_pMainDlg = this;
}

void CCppSampleDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_COMBO1, m_cbNIC);
	DDX_Control(pDX, IDC_BUTTON1, m_btnStart);
	DDX_Control(pDX, IDC_BUTTON2, m_btnStop);
	DDX_Control(pDX, IDC_CHECK1, m_btnEnableAudioStream);
	DDX_Control(pDX, IDC_EDIT1, m_Chan1Status);
	DDX_Control(pDX, IDC_EDIT2, m_Chan2Status);
	DDX_Control(pDX, IDC_EDIT3, m_Chan3Status);
	DDX_Control(pDX, IDC_EDIT4, m_Chan4Status);
}

BEGIN_MESSAGE_MAP(CCppSampleDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON1, &CCppSampleDlg::OnBnClickedButton1)
	ON_BN_CLICKED(IDC_BUTTON2, &CCppSampleDlg::OnBnClickedButton2)
	ON_WM_DESTROY()
END_MESSAGE_MAP()


// CCppSampleDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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
	VR_InitCapture(0);
	
    for (int i = 0; i < VR_GetNICCount(); i++)
    {
		CString s = VR_GetNICDescription(i);\
			s += " IP:";
		for(int j=0; j < VR_GetNICIPCount(i); j++)
		{
			if(stricmp(VR_GetNICIP(i, j), "0.0.0.0"))
			{
				s += VR_GetNICIP(i, j);
				s += ";";
			}
		}
		m_cbNIC.AddString(s);
    }

	m_btnStart.EnableWindow(TRUE);
	m_btnStop.EnableWindow(FALSE);

    if(VR_GetNICCount() > 0)
        m_cbNIC.SetCurSel(0);
	else
		m_btnStart.EnableWindow(FALSE);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CCppSampleDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 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 CCppSampleDlg::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 CCppSampleDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CCppSampleDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
	//int nIndex;

    VR_SetNIC(m_cbNIC.GetCurSel());

	//If using pcap file instead of NIC
	//VR_SetPCAPFile("C:\\SVNSrc\\sipprojectv1\\Recorder2\\PCapSamples\\IAX2\\SIP_Spykas.com.pcap");


    VR_SetChannelCount(MAX_CHAN_NUM);
	VR_SetAudioRootFolder("c:\\temp\\VR2");

	//log
    VR_SetLogLevel(4);
    VR_SetLogFileName("C:\\temp\\VR2\\VR2.txt");

	//Protocol: SIP, H323, RTP, MGCP, and SCCP or SKINNY or SKINNY_CCM71 or SCCP_CCM71, IAX2
	//VR_SetProtocol("SIP");
	//VR_SetPort(5060);

	VR_SetCB_Call_Offered(cb_call_offered);
	VR_SetCB_Call_Connected(cb_call_connected);
	VR_SetCB_Call_Idle(cb_call_idle);

	if(m_btnEnableAudioStream.GetCheck() == 1)
	{
		VR_SetCB_Call_Audio_Buffer(cb_call_audio_buffer);
	}

	//VR_SetRTPPBXCount(1);
	//VR_SetRTPPBXAddr(0, "192.168.1.220");
	//VR_SetRTPExtenCount(1);
	//VR_SetRTPExten(0, "101", "101", "192.168.1.97");

    VR_StartCapture();

	//VR_SetFilter("192.168.1.115", 1);
	//VR_SetFilter("192.168.1.116", 1);
	//VR_SetFilter("192.168.1.120", 1);
	//VR_SetFilter("8888", 1);

	m_btnStart.EnableWindow(FALSE);
	m_btnStop.EnableWindow(TRUE);

	//VR_EnableRTSrv(1);

    Capturing = true;
}

void CCppSampleDlg::OnBnClickedButton2()
{
	// TODO: Add your control notification handler code here
    VR_StopCapture();
    Capturing = false;
	m_btnStart.EnableWindow(TRUE);
	m_btnStop.EnableWindow(FALSE);
    
    //reset the ocx for next time use
    VR_FreeCapture();
    VR_InitCapture(0);

    //dataGridView1.Enabled = false;

}


void CCppSampleDlg::LogStatus(int ch, const char* strLog)
{
	switch(ch)
	{
	case 0:
		m_Chan1Status.SetWindowText(strLog);
		break;
	case 1:
		m_Chan2Status.SetWindowText(strLog);
		break;
	case 2:
		m_Chan3Status.SetWindowText(strLog);
		break;
	case 3:
		m_Chan4Status.SetWindowText(strLog);
		break;
	}
}

void CCppSampleDlg::OnDestroy()
{
	CDialog::OnDestroy();

	// TODO: Add your message handler code here
    if(Capturing)
        VR_StopCapture();

    VR_FreeCapture();

}

void CCppSampleDlg::OnCallOffered(long ChanIndex, LPCTSTR CallerIP, LPCTSTR CallerID, LPCTSTR CalleeIP, LPCTSTR CalleeID, time_t CallTime, LPCTSTR UniqueID, LPCTSTR AudioFile)
{
	// TODO: Add your message handler code here
	LogStatus(ChanIndex, "New call");

/*
	if(fpAudio[ChanIndex][0])
	{
		//close previous handle first.
		//usually it should close onCallEnd event, but here just in case
		fclose(fpAudio[ChanIndex][0]);
		fpAudio[ChanIndex][0] = NULL;
	}

	if(fpAudio[ChanIndex][1])
	{
		//close previous handle first.
		//usually it should close onCallEnd event, but here just in case
		fclose(fpAudio[ChanIndex][1]);
		fpAudio[ChanIndex][1] = NULL;
	}

	char fileName[200];
	time_t tNow = time(0);

	sprintf(fileName, "%u-%d-0.pcm", tNow, ChanIndex);
	fpAudio[ChanIndex][0] = fopen(fileName, "wb");
	sprintf(fileName, "%u-%d-1.pcm", tNow, ChanIndex);
	fpAudio[ChanIndex][1] = fopen(fileName, "wb");
*/
}

void CCppSampleDlg::OnCallConnected(long ChanIndex, LPCTSTR CallerIP, LPCTSTR CallerID, LPCTSTR CalleeIP, LPCTSTR CalleeID, time_t InitTime, time_t ConnectTime, LPCTSTR UniqueID, LPCTSTR AudioFile)
{
	// TODO: Add your message handler code here
	LogStatus(ChanIndex, "Call Connected");

/*
	char fileName[200];
	time_t tNow = time(0);

	if(!fpAudio[ChanIndex][0])
	{
		sprintf(fileName, "%u-%d-0.pcm", tNow, ChanIndex);
		fpAudio[ChanIndex][0] = fopen(fileName, "wb");
	}
	if(!fpAudio[ChanIndex][1])
	{
		sprintf(fileName, "%u-%d-1.pcm", tNow, ChanIndex);
		fpAudio[ChanIndex][1] = fopen(fileName, "wb");
	}
*/
}

void CCppSampleDlg::OnCallAudioStream(long ChanIndex, LPCTSTR UniqueID, long Direction, unsigned char* Buff, long BuffSize)
{
	char logStr[512];
	// TODO: Add your message handler code here

	sprintf(logStr, "Call Connected, received audio stream %d:%d(%x %x %x %x %x %x ...)", Direction, BuffSize, Buff[0], Buff[1], Buff[2], Buff[3], Buff[4], Buff[6]);
	LogStatus(ChanIndex, logStr);

/*
	//write the audio stream data into file
	if(Direction == 0)
	{
		if(fpAudio[ChanIndex][0])
		{
			fwrite(Buff, BuffSize, 1, fpAudio[ChanIndex][0]);
		}
	}
	else if(Direction == 1)
	{
		if(fpAudio[ChanIndex][1])
		{
			fwrite(Buff, BuffSize, 1, fpAudio[ChanIndex][1]);
		}
	}*/
}

void CCppSampleDlg::OnCallEnd(long ChanIndex, LPCTSTR CallerIP, LPCTSTR CallerID, LPCTSTR CalleeIP, LPCTSTR CalleeID, time_t InitTime, time_t ConnectTime, time_t EndTime, LPCTSTR UniqueID, LPCTSTR AudioFile, long AudioFileNum, long Reason, int CallDir, const char* sDTMF, int Codec)
{
	// TODO: Add your message handler code here
	char sLog[255];
	sprintf(sLog, "Call End. CallerIP:%s, CalleeIP:%s, Codec:%d", CallerIP, CalleeIP, Codec);
	LogStatus(ChanIndex, sLog);

/*
	if(fpAudio[ChanIndex][0])
	{
		fclose(fpAudio[ChanIndex][0]);
		fpAudio[ChanIndex][0] = NULL;
	}
	if(fpAudio[ChanIndex][1])
	{
		fclose(fpAudio[ChanIndex][1]);
		fpAudio[ChanIndex][1] = NULL;
	}
*/
}
