// Q_RoutingDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Q_Routing.h"
#include "Q_RoutingDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

// my includes
#include "Q_ROUTING_DrawNetwork.h"
#include "Q_Routing_Policy.h"
#include "Q_Routing_QRoutingPolicy.h"
#include "Q_Routing_BellmanFordPolicy.h"
#include "Q_Routing_TestBlock.h"


#define MAX_REQUEST_RATE	100

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CQ_RoutingDlg dialog

CQ_RoutingDlg::CQ_RoutingDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CQ_RoutingDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CQ_RoutingDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CQ_RoutingDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CQ_RoutingDlg)
	DDX_Control(pDX, IDC_QR_DUMP_PERCENT, m_qr_dump_percent);
	DDX_Control(pDX, IDC_BF_DUMP_PERCENT, m_bf_dump_percent);
	DDX_Control(pDX, IDC_SLIDER_REQUEST, m_slider_request);
	DDX_Control(pDX, IDC_QR_AV_TIME2, m_qr_av_time);
	DDX_Control(pDX, IDC_QR_LOAD, m_qr_load);
	DDX_Control(pDX, IDC_BF_LOAD, m_bf_load);
	DDX_Control(pDX, IDC_BF_AV_TIME, m_bf_av_time);
	DDX_Control(pDX, IDC_NETWORK2, m_network2_rect);
	DDX_Control(pDX, IDC_NETWORK1, m_network1_rect);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CQ_RoutingDlg, CDialog)
	//{{AFX_MSG_MAP(CQ_RoutingDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_DESTROY()
	ON_BN_CLICKED(IDC_RUN, OnTest)
	ON_WM_LBUTTONDBLCLK()
	ON_BN_CLICKED(IDC_STOP, OnStop)
	ON_BN_CLICKED(IDC_ONE_STEP, OnOneStep)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CQ_RoutingDlg message handlers

BOOL CQ_RoutingDlg::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
	m_slider_request.SetRange( 0 , MAX_REQUEST_RATE  );

	test_blocks = new TestBlock[2];

	test_blocks[0].Init( TestBlock::BELLMAN_FORD );
	test_blocks[1].Init( TestBlock::Q_ROUTING );
	// add some defualt routers
	int i,j,n;

/*	for( n=0 ; n<2 ; n++)
		for( i=4 ; i<6; i++ )
			for( j=4 ; j<6 ; j++ )
			{
				test_blocks[n].GetNetwork()->AddRouter( RouterPosition( i , j ) );
			}

	for( n =0 ; n<2 ; n++)
		for( i=4 ; i<6 ; i++ )
			for( j=4 ; j<6 ; j++ )
			{
				if( j+1 < 6 )
					test_blocks[n].GetNetwork()->AddConnection( test_blocks[n].GetNetwork()->GetRouter( i , j ) , test_blocks[n].GetNetwork()->GetRouter( i , j+1 ) );
				if( i+1 < 6 )
					test_blocks[n].GetNetwork()->AddConnection( test_blocks[n].GetNetwork()->GetRouter( i , j ) , test_blocks[n].GetNetwork()->GetRouter( i+1 , j ) );
			}

*/

	for( n =0 ; n<2 ; n++)
		for( i=0 ; i<6; i++ )
			for( j=0 ; j<7 ; j++ )
			{
				test_blocks[n].GetNetwork()->AddRouter( RouterPosition( i , j ) );
			}

	// add some defualt connections
	for( n =0 ; n<2 ; n++)
		for( i=0 ; i<6 ; i++ )
			for( j=0 ; j<7 ; j++ )
			{
				bool ver = true , hor = true;
				if( j==6 )
					ver = false;
				if( i==5 )
					hor = false;
				if( j==0 && ( i>0 && i<5 ) )
					ver = false;
				if( i==2 && ( j!=0 && j!=2 ) )
					hor = false;
				if( j==1 && ( i==0 || i==4) )
					hor = false;

				if( ver )
				{
					test_blocks[n].GetNetwork()->AddConnection( test_blocks[n].GetNetwork()->GetRouter( i , j ) , test_blocks[n].GetNetwork()->GetRouter( i , j+1 ) );
				}
				if( hor )
				{
					test_blocks[n].GetNetwork()->AddConnection( test_blocks[n].GetNetwork()->GetRouter( i , j ) , test_blocks[n].GetNetwork()->GetRouter( i+1 , j ) );
				}
			}
	
	for( n =0 ; n<2 ; n++)
		test_blocks[n].GetPolicy()->NetworkChange();
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

CQ_RoutingDlg::~CQ_RoutingDlg()
{
	// let all packets finish
	is_abort = true;	
	delete[] test_blocks;
}

void CQ_RoutingDlg::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 CQ_RoutingDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (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();	
		
		// Draw all networks

		CClientDC dc1( &m_network1_rect ); // device context for painting
		CRect rect1;
		m_network1_rect.GetClientRect( rect1 );
		CClientDC dc2( &m_network2_rect ); // device context for painting
		CRect rect2;
		m_network2_rect.GetClientRect( rect2 );

		DrawNetwork( *test_blocks[0].GetNetwork() , dc1 , rect1 );
		DrawNetwork( *test_blocks[1].GetNetwork() , dc2 , rect2 );

		// Update all load & avareage-time values
		CString str;
		str.Format( "%1.3f" , test_blocks[0].GetNetworkLoad() );
		m_bf_load.SetWindowText( str ); 
		str.Format( "%2.1f" , test_blocks[0].GetAverageTimePerPacket() );
		m_bf_av_time.SetWindowText( str ); 
		str.Format( "%1.3f" , test_blocks[0].GetDumpPercent() );
		m_bf_dump_percent.SetWindowText( str ); 
		str.Format( "%1.3f" , test_blocks[1].GetNetworkLoad() );
		m_qr_load.SetWindowText( str ); 
		str.Format( "%2.1f" , test_blocks[1].GetAverageTimePerPacket() );
		m_qr_av_time.SetWindowText( str ); 
		str.Format( "%1.3f" , test_blocks[1].GetDumpPercent() );
		m_qr_dump_percent.SetWindowText( str ); 

	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CQ_RoutingDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CQ_RoutingDlg::OnDestroy() 
{
	CDialog::OnDestroy();
	
	// TODO: Add your message handler code here
}

void CQ_RoutingDlg::OnTest() 
{
	// TODO: Add your control notification handler code here

/*
	static bool first_time = true;
		
	Packet packet_data;
	packet_data.source = &test_blocks[0].GetNetwork()->GetRouter( 3,3 );
	packet_data.destination = &test_blocks[0].GetNetwork()->GetRouter( 5,5 );
	if( first_time )
		test_blocks[0].SendPacket( packet_data );
	first_time = false;
	test_blocks[0].OneStep();
*/
	
	//OneStep();

	is_abort = false;
	AfxBeginThread( RunningLoop , this );
}

UINT CQ_RoutingDlg::RunningLoop( LPVOID pParam )
{
	static is_running = false;
	if( is_running )
		return 0;
	is_running = true;

	CQ_RoutingDlg* dlg = (CQ_RoutingDlg*)pParam;

	while( !dlg->is_abort ){
		dlg->OneStep();

		//Sleep( 100 );
	}

	is_running = false;
	return 1;
}

void CQ_RoutingDlg::OneStep()
{
	// file for debug inspect
	static int step_counter = 0;
	static FILE * file = 0;
	if( !file )
	{
		file = fopen( "debug.txt" , "w" );
		fprintf( file , "BellmanFord,,Q-Learning\n" );
		fprintf( file , "time per packet,dump percent,time per packet,dump percent\n" );

	}
	if( step_counter++ % 100 == 0 )
	{
		fprintf( file , "%3.1f,%1.3f,%3.1f,%1.3f\n" ,
				test_blocks[0].GetAverageTimePerPacket() , test_blocks[0].GetDumpPercent() ,
				test_blocks[1].GetAverageTimePerPacket() , test_blocks[1].GetDumpPercent() );
	}
	
	// make some requests, according to requests rate
	
	// create packets
	for( int i=0 ; i< ( m_slider_request.GetPos() + 19 ) / 20 ; i++)
	{
		Network & network = *test_blocks[0].GetNetwork();
		// create packet
		Packet packet_data;
		int j;
		int source_index = rand() % network.GetRouterNum();
		int dest_index = rand() % network.GetRouterNum();
		for( int n =0 ; n <2 ; n++ )
		{
			RouterListIterator i;
			test_blocks[n].GetNetwork()->InitRouterListIterator( i );
			for( i.Begin() , j=0 ; j< source_index ; j++ )
				i++;
			packet_data.source = i.GetRouter();
			for( i.Begin() , j=0 ; j< dest_index ; j++ )
				i++;
			packet_data.destination = i.GetRouter();
			// send the packet
			test_blocks[n].SendPacket( packet_data );
		}
	}

	// process one step at each network
	for( int j=0 ; j<2 ; j++ )
		test_blocks[j].OneStep();

	// redraw networks
	OnPaint();
}

void CQ_RoutingDlg::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	
	CDialog::OnLButtonDblClk(nFlags, point);
}

void CQ_RoutingDlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	is_abort = true;	
}

void CQ_RoutingDlg::OnOneStep() 
{
	// TODO: Add your control notification handler code here
	OneStep();
}
