#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <assert.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <qbuttongroup.h>
#include <qcombobox.h>
#include <qkeycode.h>
#include <qmenubar.h>
#include <qmessagebox.h>
#include <qpopupmenu.h>
#include <qpixmap.h>
#include <qworkspace.h>

#include "CamStreamApp.h"
#include "CamStreamMainWindow.h"
#include "CamWindow.h"

#include "gui/OpenDevice.h"
#include "WebCamViewer.h"


/**
  \class CCamStreamMainWindow
  \brief Name says it all: main window, with menu bar, etc.
  
  This is the main widget class of the application; It does several things:
  
  * manages the main menu and the Frames of the various subclasses. 
  * handles new and disappearing devices. 
  
  There is only one instance of this object, ever.
*/



/**
  \brief Constructor
*/
CCamStreamMainWindow::CCamStreamMainWindow()
	: QMainWindow(0, "camstreams")
{
   QPopupMenu *file, *window;
   QMenuBar *pMenu;
   QPixmap BackgroundPix;

   // Create main workspace, with a nice background
   if (!BackgroundPix.load(SHARE_DIR "/icons/canvas.png")) {
     qWarning("Failed to load " SHARE_DIR "/icons/canvas.png!");
     BackgroundPix.fill(lightGray);
   }
   Workspace = new QWorkspace(this); // Just a placeholder for all the windows
   assert(Workspace != NULL);
   Workspace->setBackgroundPixmap(BackgroundPix);

   file = new QPopupMenu();
   file->insertItem("&Open viewer...",   this, SLOT(FileOpenNewViewer()), CTRL + Key_O);
   file->insertItem("E&xit", this, SLOT(CloseAll()), CTRL + Key_Q);

   window = new QPopupMenu();
   window->insertItem("&Cascade", Workspace, SLOT(cascade()));
   window->insertItem("&Tile",    Workspace, SLOT(tile()));

   pMenu = menuBar();
   pMenu->insertItem("&File", file);
   pMenu->insertItem("&Window", window);

   setCentralWidget(Workspace);

#if 0
   // Add devices on command line as viewers
   m = CamApp->argc();
   for (i = 1; i < m; i++) {
      const char *dev;

      dev = CamApp->argv()[i];
      fd = open(dev, O_RDONLY);
      if (fd < 0) {
        QMessageBox mb;
        QString message;
        
        message.sprintf("Failed to open video device: %s" , dev);
        mb.critical(0, "Failure", message);
      }
      else {
        pCam = new CCamWidget(fd, Workspace);
        AddCam(pCam);
      }
   }
#endif
}

CCamStreamMainWindow::~CCamStreamMainWindow()
{
qDebug("CCamStreamMainWindow::~CCamStreamMainWindow()");
   CloseAll();
}

// private slots

void CCamStreamMainWindow::CloseAll()
{
   QWidgetList wl;
   QWidget *w;
   
   wl = Workspace->windowList();
   for (w = wl.first(); w != 0; w = wl.next())
      delete w;
   qApp->quit();
}


/* Menu functions */

/** 
  \brief Show dialog to open new viewer frame
  
  This function will pop-up a small dialog where the user can select
  a (detected) video device, and an initial size.
 */
void CCamStreamMainWindow::FileOpenNewViewer()
{
   COpenDeviceDlg Dlg(this, "open video device dlg", true);
   QString dname;
   CVideoDevice *pDev;
   CCamWindow *pWindow;
   QSize ls;
   QButton *sizebutton;
   int i;

   for (i = 0; i < CamApp->VideoDevices->NumberOfVideoDevices(); i++) {
      pDev = CamApp->VideoDevices->GetVideoDevice(i);
      dname = pDev->GetIntfName();
      if (dname.isNull())
        dname = pDev->GetNodeName();
      Dlg.m_DeviceSelection->insertItem(dname);
   }
   if (Dlg.exec() == QDialog::Accepted) {
     i = Dlg.m_DeviceSelection->currentItem();
     pDev = CamApp->VideoDevices->GetVideoDevice(i);
     if (pDev == NULL)
       return;
#if TRACE_CANVAS_OPEN
     //ls = Dlg.GetInitialSize();
     //printf("Opening %s, requested size = %dx%d\n", (const char *)pDev->GetNodeName(), ls.width(), ls.height());
#endif
     sizebutton = Dlg.m_InitialSize->selected();
     if (sizebutton != NULL)
     i = Dlg.m_InitialSize->id(sizebutton);
     switch(i) {
       case 1: ls = QSize(128,  96); break;
       case 2: ls = QSize(160, 120); break;
       case 3: ls = QSize(176, 144); break;
       case 4: ls = QSize(320, 240); break;
       case 5: ls = QSize(352, 280); break;
       case 6: ls = QSize(640, 480); break;
       case 7: ls = pDev->GetMaxSize(); break;
       default: ls = QSize(0, 0); break;
     }
     pWindow = new CWebCamViewer(pDev, ls, Workspace);
     if (pWindow == NULL) {
       QMessageBox::warning(this, tr("Error creating viewer"),
                    tr("The viewer could not be created. You might be running low on memory."), 
                    QMessageBox::Ok, QMessageBox::NoButton);
     }
     else
       pWindow->show();
   }
}



