#include "MGMonteCarloMain.h"

#include <TSystem.h>        // gSystem

#include <TGTab.h>          // TGTab
#include <TGMenu.h>         // TGPopupMenu
#include <TGButton.h>       // TGTextButton
#include <TGMsgBox.h>       // TGMsgBox
#include <TGListBox.h>      // TGListBox
#include <TGFSContainer.h>  // TGFileContainer

// FIXME: Move to MAGIC.h
#define S_ISDIR(m) (((m)&(0170000)) == (0040000))  

ClassImp(MGMonteCarloMain)

enum CommandDataChecker {
  M_FILE_CLOSE , 
  M_BUTTON_ACTION, 

  M_PBUTTON_CDIR_UP, 
  M_PBUTTON_LIST_MODE, 
  M_PBUTTON_DETAIL_MODE 
} ; 


MGMonteCarloMain::MGMonteCarloMain(const TGWindow *p, const TGWindow *main, 
                            UInt_t w, UInt_t h ) 
        : TGTransientFrame(p, main, w, h ) 
{
  //
  //    Main window to controll the october test
  //

  //    set non-gui members to starting values 

  sprintf ( fInputFile, "\n" ) ; 

  //
  //    First create the MenuBar.   
  //

  //     Layout objects for menue. 

  fLayMenuBar = new TGLayoutHints ( kLHintsTop | kLHintsLeft | kLHintsExpandX, 2, 2, 2, 2 ) ; 
  fLayMenuItem = new TGLayoutHints ( kLHintsTop | kLHintsLeft , 0, 4, 0, 0 ) ; 
  
  //  crate the menu bar

  fFileMenu = new TGPopupMenu ( fClient->GetRoot() ) ; 
  fFileMenu->AddEntry ("Close", M_FILE_CLOSE ) ; 
  fFileMenu->Associate(this) ; 
  
  //  the button messages are handled by main frame (this) 

  fMenuBar = new TGMenuBar ( this, 1, 1, kHorizontalFrame ) ; 
  fMenuBar->AddPopup("File", fFileMenu, fLayMenuItem ) ;   
  AddFrame(fMenuBar, fLayMenuBar ) ; 
  
  //
  //    Create the top window with a lot of buttons 
  //

  fFrameTop = new TGCompositeFrame (this, 300,100, kVerticalFrame ) ; 
  
  fTop1 = new TGHorizontalFrame (fFrameTop, 300, 100 ) ; 

  fButAction = new TGTextButton(fTop1, "ACTION", M_BUTTON_ACTION );
  fButAction->Associate(this) ;   
  fTop1->AddFrame (fButAction, new TGLayoutHints(kLHintsTop | kLHintsLeft, 10, 10, 5, 5) );
  
  fFrameTop->AddFrame (fTop1, new TGLayoutHints(kLHintsCenterX, 10, 10, 5, 5) );

  AddFrame(fFrameTop, new TGLayoutHints (kLHintsTop ) ) ;   


  //
  //    Create the low window with a tabs in it
  //

  fFrameLow = new TGCompositeFrame (this, 300,100, kHorizontalFrame ) ; 
  
  fLayTab = new TGLayoutHints ( kLHintsExpandX   , 5, 5, 5, 5 ) ;

  //    create the first tab

  fTab = new TGTab ( fFrameLow, 400, 400 ) ;   

  TGCompositeFrame *tf = fTab->AddTab("Input File") ; 
  
  fTabF1 = new TGCompositeFrame (tf, 100, 100, kHorizontalFrame) ; 
  //  tf->AddFrame(fTabF1, fLayTab ) ; 

  
  fTabF1a = new TGCompositeFrame (tf, 100, 100, kHorizontalFrame) ; 
  tf->AddFrame(fTabF1a,  new TGLayoutHints ( kLHintsTop | kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5 ) ) ; 

  fTabF1b = new TGCompositeFrame (tf, 100, 100, kVerticalFrame) ; 
  //  tf->AddFrame(fTabF1b,  new TGLayoutHints ( kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY  , 5, 5, 5, 5 ) ) ; 
  tf->AddFrame(fTabF1b,  new TGLayoutHints ( kLHintsExpandX | kLHintsExpandY  , 5, 5, 5, 5 ) ) ; 

  
  fDir = new TGListBox(fTabF1a, -1) ; 
  fDir->Resize(350,20) ;
  char temp[100] ; 
  //  sprintf ( temp, "%s", START_DIRECTORY ) ; 
  sprintf ( temp, "%s", gSystem->WorkingDirectory()  ) ; 
  fDir->AddEntry(temp, 1) ; 
  fTabF1a->AddFrame( fDir, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX, 5, 5, 5, 5 ) ) ; 


  fPicCdup = fClient->GetPicture("tb_uplevel.xpm") ; 
  fCdup = new TGPictureButton(fTabF1a, fPicCdup, M_PBUTTON_CDIR_UP ) ; 
  fCdup->SetToolTipText("One Level up!") ; 
  fCdup->Associate(this) ; 
  fTabF1a->AddFrame (fCdup, new TGLayoutHints(kLHintsLeft | kLHintsTop, 5, 5, 5, 5) ) ; 

  fPicList = fClient->GetPicture("tb_list.xpm") ; 
  fListMode = new TGPictureButton(fTabF1a, fPicList, M_PBUTTON_LIST_MODE ) ; 
  fListMode->SetToolTipText("List Mode") ; 
  fListMode->Associate(this) ; 
  fListMode->SetState(kButtonUp) ; 
  fListMode->AllowStayDown(kTRUE) ; 
  fListMode->AllowStayDown(kTRUE) ;  fTabF1a->AddFrame (fListMode, new TGLayoutHints(kLHintsLeft | kLHintsTop, 5, 5, 5, 5) ) ;

  fPicDetail = fClient->GetPicture("tb_details.xpm") ; 
  fDetail = new TGPictureButton(fTabF1a, fPicDetail, M_PBUTTON_DETAIL_MODE ) ; 
  fDetail->SetToolTipText("Details Mode") ; 
  fDetail->Associate(this) ; 
  fDetail->SetState(kButtonEngaged) ; 
  fDetail->AllowStayDown(kTRUE) ; 
  fTabF1a->AddFrame (fDetail, new TGLayoutHints(kLHintsLeft | kLHintsTop, 5, 5, 5, 5) ) ; 

    
  fFileView = new TGListView(fTabF1b, 540, 380 ) ; 
  fFileCont = new TGFileContainer(fFileView->GetViewPort(), 100, 100,
				  kVerticalFrame, fgWhitePixel) ; 

  fFileCont->Associate(this) ; 
  fFileView->GetViewPort()->SetBackgroundColor(fgWhitePixel) ; 
  fFileView->SetContainer(fFileCont) ; 
  fFileCont->SetFilter("*") ; 
  //  fFileCont->ChangeDirectory(START_DIRECTORY) ; 
  fFileCont->ChangeDirectory(gSystem->WorkingDirectory()) ; 
  fFileView->SetViewMode(kLVDetails); 
  fFileCont->Sort(kSortByName) ; 
  
  fTabF1b->AddFrame(fFileView, new TGLayoutHints(kLHintsTop | kLHintsExpandX | kLHintsExpandY, 5, 5, 5, 5) ) ; 

  tf->AddFrame(fTabF1, fLayTab) ;
 
  fFrameLow->AddFrame ( fTab, new TGLayoutHints(kLHintsBottom | kLHintsExpandX | kLHintsExpandY, 5, 5, 5, 5) ); 

  AddFrame(fFrameLow, new TGLayoutHints (kLHintsExpandX|kLHintsExpandY) ) ; 

  //
  //   Map the window, set up the layout, etc. 
  //

  SetWMSizeHints(200, 250, 1000, 1000, 10, 10 ) ;      // set the smallest and biggest size of the Main frame

  MapSubwindows();
  
  Layout();
  
  SetWindowName("MonteCarlo Main");
  SetIconName("MonteCarlo");
  
  MapWindow();

} 


// ======================================================================
// ======================================================================

MGMonteCarloMain::~MGMonteCarloMain()
{
  //delete  fPicCdup, fPicList, fPicDetail; 
    delete fLayTab;
    delete fLayMenuBar;
    delete fLayMenuItem;
    delete fFileView;
    delete fFileCont;
    delete fCdup;
    delete fListMode;
    delete fDetail;
    delete fDir ;
    delete fTabF1b;
    delete fTabF1a;
    delete fTabF1;
    delete fButAction; 
    delete fTop1;
    delete fTab;
    delete fFrameTop;
    delete fFrameLow;
    delete fFileMenu;
    delete fMenuBar;

} 


// ======================================================================
// ======================================================================

void MGMonteCarloMain::CloseWindow()
{
   // Got close message for this MainFrame. Calls parent CloseWindow()
   // (which destroys the window) and terminate the application.
   // The close message is generated by the window manager when its close
   // window menu item is selected.

  delete this ; 
}


// ======================================================================
// ======================================================================

Bool_t MGMonteCarloMain::InputFileSelected() 
{
  //   Checks if there is a selected input root file
   
  if ( strcmp ( fInputFile, "\n") == 0 )
    { 
      return ( kFALSE ) ; 
    } 
  
  return (kTRUE) ; 
} 


// ======================================================================
// ======================================================================

Bool_t MGMonteCarloMain::ProcessMessage(Long_t msg, Long_t parm1, Long_t)
{     
  // Process events generated by the buttons in the frame.
  
  Int_t   buttons = 4, retval = 0 ; 
  Char_t  wort[100] ;
  Char_t  extens[5] ;
  Char_t  command[110] ;
 
  TGFileItem *item ;     // to process items in the file view container
  void *np = NULL ;      // null pointer

  switch (GET_MSG(msg)) 
    {
    case kC_COMMAND:
      switch (GET_SUBMSG(msg)) 
	{
	case kCM_BUTTON:
	  
	  switch (parm1)
	    {  

	    case M_BUTTON_ACTION:
	      	
	      if ( InputFileSelected() == kFALSE ) {              // it is not selected
		
		new TGMsgBox(fClient->GetRoot(), this, "ERROR!", 
			     "No Input (root) File selected!", kMBIconExclamation, buttons, &retval);
		break ; 
	      }      
	      
	      new TGMsgBox(fClient->GetRoot(), this, "INFORMATION!", 
			   "Put Intelligence here!!!", kMBIconExclamation, buttons, &retval);

	      break ; 
		  
	    case M_PBUTTON_CDIR_UP :

	      //  goto the parent directory
	      
	      gSystem->ChangeDirectory("..") ; 
	      fDir->RemoveEntry(1) ; 
	      sprintf (wort, "%s", gSystem->WorkingDirectory() ) ; 
	      fDir->AddEntry(wort,1) ; 
	      fDir->MapSubwindows() ; 
	      fDir->Layout() ; 
	      fFileCont->ChangeDirectory( wort ) ; 
	      fFileCont->DisplayDirectory() ; 
	      
	      break ; 
	    
	    case M_PBUTTON_LIST_MODE:
	      fFileView->SetViewMode(kLVList) ; 
	      fDetail->SetState(kButtonUp) ; 
	      
	      break ; 
	      
	    case M_PBUTTON_DETAIL_MODE:
	      fFileView->SetViewMode(kLVDetails) ; 
	      fListMode->SetState(kButtonUp) ; 
	      
	      break ;
	      
	    default:
	      break ;
	    } 

	case kCM_MENU:

	  switch (parm1) {
	  case M_FILE_CLOSE:
	    CloseWindow() ; 

	    break; 
	  }
	  break ;
	  
	default:
	  break ;
	  
	}
      
    case kC_CONTAINER: 
      switch (GET_SUBMSG(msg)) {
	
	//      case kCT_ITEMCLICK:
	// 	printf ("itemclick\n"); 
	//      break; 
	
      
      case kCT_ITEMDBLCLICK: 
	//
	//  process the double click in the file view container
	//
	
	if ( parm1 == kButton1) {
	  if ( fFileCont->NumSelected() == 1 ) {   
	    //
	    //  one file selected
	    //	  
	    item = (TGFileItem *) fFileCont->GetNextSelected(&np) ; 
	    
	    if ( S_ISDIR(item->GetType()) )   // file is directory
	      {  
		//  goto directory 
		
		sprintf (wort, "%s", item->GetItemName()->GetString()) ;
		fFileCont->ChangeDirectory ( wort ) ; 
		gSystem->ChangeDirectory( wort ) ; 
		
		sprintf (wort, "%s", gSystem->WorkingDirectory() ) ; 
		fDir->RemoveEntry(1) ; 
		fDir->AddEntry( wort, 1 ) ; 
		fDir->MapSubwindows() ; 
		fDir->Layout() ; 
	      }
	    else                              // file is no directory, is a file 
	      { 
		sprintf (wort, "%s", item->GetItemName()->GetString() ) ; 
	    
		//    determine the file type by extensions
		
		for (Int_t i = 0 ; i<5; i++) 
		  extens[i] = '\0' ; 
		
		for ( Int_t i=0; wort[i] != '\0'; i++) {
		  if ( wort[i] == '.') {
		    strncpy (extens, &wort[i+1], 4 ) ; 
		    break ; 
		  }
		}
		
		if ( ! strcmp(extens, "ps") ) {              //     postscript file
		  sprintf ( command, "gv %s/%s &", 
			    gSystem->WorkingDirectory(), 
			    wort ) ; 
		  gSystem->Exec(command) ; 
		  break ; 
		}
		else if  ( ! strcmp(extens, "root") ) {      //     root file
		  sprintf ( fInputFile, "%s/%s" , gSystem->WorkingDirectory(), wort ) ;  

		  printf (" %s \n", fInputFile ) ; 
		  break ; 
		}
		
	      } 
	  }
	}
	break; 
	
      default:
	break ;
      }
      
      
      
    default:
      break;
    }
  return kTRUE;
} 
