/**
  \class CVideoCollector
  
  Collects all video devices it can find. This is a singleton object (meaning
  there is only instance of it, ever).
  
  To turn debugging on, #define TRACE_VIDEOCOLLECTOR
  
*/

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

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

#include <qdir.h>
#include <qfileinfo.h>
              
#include "VideoCollector.h"

CVideoCollector *CVideoCollector::Collector = NULL;

CVideoCollector::CVideoCollector()
{
   Scan();
}


// private

/**
  \fn void CVideoCollector::Scan()
  \brief Sans /dev/video for available devices
  
  Argh. This is the second time Qt bites me in /dev: IT WON'T BLOODY LIST
  DEVICE INODES!!! So back to plain old sprintf().
  
*/
void CVideoCollector::Scan()
{
   char devname[40];
   struct stat devstat;
   int i;
   CVideoDevice *v;

   for (i = 0; i < 64; i++) {
      sprintf(devname, "/dev/video%d", i);
      if (stat(devname, &devstat) == 0) {
#ifdef TRACE_VIDEOCOLLECTOR
        printf("CVideoCollector: testing %s\n", devname);
#endif   
        if (!S_ISLNK(devstat.st_mode)) {
          v = new CVideoDevice(devname);
          if (!v->IsValid()) { // The class detects if this is a valid device
            delete v;
            v = NULL;
          }
          if (v)
            Devices.append(v);
        } // .. if !S_ISLNK
      } // ..if !stat
   } // ..for i
}

// public

CVideoCollector *CVideoCollector::Instance()
{
   if (Collector == NULL)
     Collector = new CVideoCollector();
   return Collector;
}


int CVideoCollector::NumberOfVideoDevices() const
{
   return Devices.count();
}

CVideoDevice *CVideoCollector::GetVideoDevice(int n)
{
   return Devices.at(n);
}
