// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "CTMS.h"

#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_WM_TIMER()
	ON_COMMAND(ID_TDI_EXPAND, OnTdiExpand)
	ON_WM_ERASEBKGND()
	ON_COMMAND(ID_REFRESH, OnRefresh)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
  ID_INDICATOR_RX2,
  ID_INDICATOR_RX,
  ID_INDICATOR_TX2,
  ID_INDICATOR_TX,
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	// TODO: add member initialization code here
	m_iTimerId = 0; //invalid timer reference
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}

//	if (!m_wndStatusBar.Create(this) ||
//		!m_wndStatusBar.SetIndicators(indicators,
//		  sizeof(indicators)/sizeof(UINT)))
	if (!m_wndStatusBar.CreateStatusBar( this, indicators, sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}

  //no borders for the text
  m_wndStatusBar.SetStyle( 1, SBPS_NOBORDERS);
  m_wndStatusBar.SetFgColor( 1, m_wndStatusBar.GetFgColor(1), m_wndStatusBar.GetFgColor(1));
  m_wndStatusBar.SetStyle( 3, SBPS_NOBORDERS);
  m_wndStatusBar.SetFgColor( 3, m_wndStatusBar.GetFgColor(3), m_wndStatusBar.GetFgColor(3));

  //just some bitmaps..
  m_wndStatusBar.SetStyle( 2, SBPS_NOBORDERS);
  m_wndStatusBar.SetMode( 2, XSB_BITMAP);
  m_wndStatusBar.SetBitmap( 2, "GRAY_LED", "GRAY_LED");
  m_wndStatusBar.SetStyle( 4, SBPS_NOBORDERS);
  m_wndStatusBar.SetMode( 4, XSB_BITMAP);
  m_wndStatusBar.SetBitmap( 4, "GRAY_LED", "GRAY_LED");

  //Do not show the documnet name in the title bar
  ModifyStyle( FWS_ADDTOTITLE, 0, 0);

	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

  // Set the class name to be the app's single instance class name 
  cs.lpszClass = ((CCTMSApp *)AfxGetApp())->GetMainFrameClass();
	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers


BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT /*lpcs*/, CCreateContext* pContext) 
{
	// TODO: Add your specialized code here and/or call the base class
	CRect rect;
	GetClientRect(&rect);

  
	// CG: The following block was added by the Splitter Bar component.
	{

		if (!m_wndSplitter.CreateStatic(this, 1, 2))
		{
			TRACE0("Failed to create splitter bar ");
			return FALSE;    // failed to create
		}

	}

	// TODO: Add your specialized code here and/or call the base class

  // add the first splitter pane - this is always a tree
	if (!m_wndSplitter.CreateView(0, 0, RUNTIME_CLASS( CCTMSTreeView), CSize( rect.Width()/4,rect.Height()), pContext))
	{
		TRACE0("Failed to create first pane\n");
		return FALSE;
	}

	// add the second splitter pane, in fact the size doesn't matter
	if (!m_wndSplitter.CreateView(0, 1, pContext->m_pNewViewClass, CSize( rect.Width()/4,rect.Height()), pContext))
	{
		TRACE0("Failed to create second pane\n");
		return FALSE;
	}

	// activate the tree view
	SetActiveView((CView*)m_wndSplitter.GetPane(0,0));
  
  //original return method os no longer used, it overrules the splitter
  //return CFrameWnd::OnCreateClient(lpcs, pContext);

  //start timer for connection builds
  m_iTimerId = SetTimer( TIMER_MAINFRAME, TIME_MAINFRAME, NULL);
  return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// BOOL CMainFrame::ReplaceView(CRuntimeClass *pViewClass, int SubId)
// 
// 
/////////////////////////////////////////////////////////////////////////////
BOOL CMainFrame::ReplaceView(CRuntimeClass *pViewClass, int SubId)
{

  CCreateContext context;
  BOOL bSetActive = FALSE;
	       
 
  //Get pointer to CDocument object so that it can be used in the creation 
  //process of the new view
  CDocument * pDoc = ((CView *)m_wndSplitter.GetPane( 0, 1))->GetDocument();
  CView * pActiveView = GetActiveView();
  ((CCTMSApp *)AfxGetApp())->SetTMIndex( SubId);

  if (pActiveView == NULL || pActiveView == m_wndSplitter.GetPane( 0, 1)) 
    bSetActive=TRUE;

  //set flag so that document will not be deleted when view is destroyed
  pDoc->m_bAutoDelete=FALSE;    

  // Delete existing view 
  ((CView *)m_wndSplitter.GetPane( 0, 1))->DestroyWindow();

  // set flag back to default 
  pDoc->m_bAutoDelete=TRUE;

  // Create new view                      
  context.m_pNewViewClass=pViewClass;
  context.m_pCurrentDoc=pDoc;
  context.m_pNewDocTemplate=NULL;
  context.m_pLastView=NULL;
  context.m_pCurrentFrame=NULL;

  m_wndSplitter.CreateView( 0, 1, pViewClass, CSize( 0, 0), &context);

  CView * pNewView= (CView *)m_wndSplitter.GetPane( 0, 1);

  if (bSetActive==TRUE)
    SetActiveView(pNewView);

  //recalculate the views
  m_wndSplitter.RecalcLayout(); 
  ((CView *)m_wndSplitter.GetPane( 0, 1))->OnInitialUpdate();
  return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// void CMainFrame::OnTimer(UINT nIDEvent) 
// 
// 
/////////////////////////////////////////////////////////////////////////////
void CMainFrame::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	if (nIDEvent == TIMER_MAINFRAME)
  {

//    //find the last TDI
//    int index = ((CCTMSApp *)AfxGetApp())->GetLastTDI();

//    //we need atlest one element
//    if (index)
//    {

//	    CTDI *tdi = ((CCTMSApp *)AfxGetApp())->GetTDI( index-1);

//      //do a connection loop
//      tdi->Connection();

//      //if there is connection, add this one to the tree-view
//      if (tdi->IsConnected())
//      {

//        //add the current TDI to the tree-view
//        CCTMSTreeView *pTreeView = (CCTMSTreeView *)m_wndSplitter.GetPane( 0, 0);
//        pTreeView->AddTDI( pTreeView->GetTreeCtrl().GetRootItem( ), TVI_LAST, tdi->m_sTDIName, index-1);

//        //if it is the first TDI, expand the root item
//        pTreeView->ExpandRoot();

//        //create a new (not connected) TDI
//        ((CCTMSApp *)AfxGetApp())->AddTDI(); //last one is not connected...
//        index++;
//        OnRefresh();
//      }
    }
//    else
//    {

//      ((CCTMSApp *)AfxGetApp())->AddTDI();
//      index++;
//      OnRefresh();
//    }

//    int i;

/*    //do all the communication we have to do
    for (i = 0; i < (index-1); i++)
    {

      CTDI *tdi = ((CCTMSApp *)AfxGetApp())->GetTDI( i);

      //check if there is there is still a connection
      if (!tdi->IsConnected())
      {

        int k, m;
        HTREEITEM hItem;
        CCTMSTreeView *pTreeView = (CCTMSTreeView *)m_wndSplitter.GetPane( 0, 0);

        for (m = i+1; m < (index-1); m++)
        {

          hItem = pTreeView->GetTreeCtrl().GetRootItem();
          hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_CHILD);

          for ( k = 0; k < m; k++)
            hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_NEXT);

          //rebuild the tree view
          pTreeView->ReindexTDI(hItem, m - 1);
        }

        //remove TDI from the list
        ((CCTMSApp *)AfxGetApp())->RemoveTDI( i);

        //remove item from treeview
        hItem = pTreeView->GetTreeCtrl().GetRootItem();
        hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_CHILD);

        for ( k = 0; k < i; k++)
          hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_NEXT);

        pTreeView->GetTreeCtrl().DeleteItem( hItem);

        index--;

        OnRefresh();
      }
      //else
      //  tdi->Communication(); //normal communication
    }
  }
*/

//  CTDI *tdi = ((CCTMSApp *)AfxGetApp())->GetTDI();

  //update the receive led
  if (((CCTMSApp *)AfxGetApp())->GetRecvBit())
    m_wndStatusBar.SetBitmap( 2, "GREEN_LED", "GREEN_LED");
  else
    m_wndStatusBar.SetBitmap( 2, "GRAY_LED", "GRAY_LED");
  ((CCTMSApp *)AfxGetApp())->SetRecvBit( 0);


  //update transmit led
  if (((CCTMSApp *)AfxGetApp())->GetSendBit())
    m_wndStatusBar.SetBitmap( 4, "RED_LED", "RED_LED");
  else
    m_wndStatusBar.SetBitmap( 4, "GRAY_LED", "GRAY_LED");
  ((CCTMSApp *)AfxGetApp())->SetSendBit( 0);

	CFrameWnd::OnTimer(nIDEvent);
}

/////////////////////////////////////////////////////////////////////////////
// void CMainFrame::OnTdiExpand() 
// 
// 
/////////////////////////////////////////////////////////////////////////////
void CMainFrame::OnTdiExpand() 
{
	// TODO: Add your command handler code here
  CCTMSTreeView *pTreeView = (CCTMSTreeView *)m_wndSplitter.GetPane( 0, 0);
//  int k;

  HTREEITEM hItem = pTreeView->GetTreeCtrl().GetRootItem();
  hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_CHILD);

//  for ( k = 0; k < ((CCTMSApp *)AfxGetApp())->GetLastTDI()-1; k++)
//  {
//    if (hItem) pTreeView->GetTreeCtrl().Expand( hItem, TVE_COLLAPSE);
//    hItem = pTreeView->GetTreeCtrl().GetNextItem( hItem, TVGN_CHILD);
//  }

  pTreeView->ExpandRoot();
}

BOOL CMainFrame::OnEraseBkgnd(CDC* /*pDC*/) 
{
	// TODO: Add your message handler code here and/or call default
	return TRUE;
	//return CFrameWnd::OnEraseBkgnd(pDC);
}

void CMainFrame::OnRefresh() 
{
	// TODO: Add your command handler code here
	m_wndSplitter.GetPane( 0, 1)->SendMessage( WM_COMMAND, (unsigned int)ID_REFRESH);
}

BOOL CMainFrame::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	//kill our timer, if there is one
  if (m_iTimerId)
    KillTimer( m_iTimerId);

  m_iTimerId = 0;

	return CFrameWnd::DestroyWindow();
}
