#include "vidconf.h"
#include <qapp.h>
#include <aviplay.h>
#include <videoencoder.h>
#include <VideoDPMS.h>
#include <stdlib.h>
#include <unistd.h>
#include <cpuinfo.h>
#include <version.h>
#include "vidcapreg.h"
#include "v4lwindow.h"
#include "v4lxif.h"
#include "qplatinumstyle.h"
#include "qwindowsstyle.h"
#include <errno.h>
#include <stdio.h>
#include <iostream>
#include <sys/time.h>
#include <sys/resource.h>
#include <linux/kernel.h>
unsigned int m_iMemory;
extern "C" void sysinfo(struct sysinfo * val);

using namespace std;

static v4lxif* createDevice()
{
    v4lxif* v4l=0;
    v4l=0;
    try
    {
	v4l=new v4l1if(0, RS("CapDev", "/dev/video").c_str());
    }
    catch(FatalError& e)
    {
	e.PrintAll();
	return 0;
    }
    
    return v4l;
}
class QMyApp: public QApplication
{
    V4LWindow* m_pWin;
public:
    QMyApp(int argc, char** argv): QApplication(argc, argv), m_pWin(0){}
    void setWindow(V4LWindow* pWin) { m_pWin=pWin; }
    virtual bool     x11EventFilter( XEvent * e )
    {
	if(m_pWin)
	    m_pWin->get_clips();
	return QApplication::x11EventFilter(e);
    }
};
int main(int argc, char** argv)
{
//    Registry::ReadString("QtVidcap", "CapDev", "/dev/video");
    QMyApp a(argc,argv);
//    QPlatinumStyle* qps=new QPlatinumStyle;
    QWindowsStyle* qps=new QWindowsStyle;
    a.setStyle(qps);

    if (GetAvifileVersion()!=AVIFILE_VERSION)
    {
	cout<<"This binary was compiled for Avifile ver. "<<AVIFILE_VERSION<<", but the library is ver. "<<GetAvifileVersion()<<". Aborting."<<endl;
	return 0;
    }
    bool bNow=false;
    if((argc==2) && (!strcmp(argv[1], "-now")))
	bNow=true;
    string cmd="kv4lsetup -l "+ RS("CapDev", "/dev/video");
    if ((cmd.find(':')!=string::npos)
	|| (cmd.find('|')!=string::npos)
	|| (cmd.find(';')!=string::npos))
	{
	    system("kv4lsetup");
//	    printf("Retval: %d errno: %d\n", val, errno);
	}
    else
    {
	system(cmd.c_str());
//	printf("str: %s\n", cmd.c_str());
//        printf("Retval: %d errno: %d\n", val, errno);
    }
#ifdef __linux__    
    struct sysinfo s_info;
    sysinfo(&s_info);
    m_iMemory=s_info.totalram;
    if(m_iMemory<2*1048576)
	m_iMemory=1048576;
    else
	m_iMemory/=2;
    cout<<"Using "<<m_iMemory/1048576<<" Mb of memory for frame caching"<<endl;
#else
    m_iMemory=10000000;
#endif    
    int result;

    int p = getpriority(PRIO_PROCESS, 0);
    //attention: only root is allowed to lower priority
    setpriority(PRIO_PROCESS, 0, (p + 3 < 20) ? p + 3 : 20);

    while(1)
    {    
	v4lxif* pV4L=createDevice();
	if(pV4L)
	{
	    V4LWindow m(pV4L);
	    VideoDPMS dp(m.x11Display());
	    if(bNow)
		m.setAutoRecord();
	    m.show();
	    m.setupDevice();
	    a.setWindow(&m);
	    a.setMainWidget(&m);
	    a.exec();
	    return 0;
	}
	else
	{
	    VidConfig conf(0, pV4L);
	    if(conf.exec()==QDialog::Rejected)
		return -1;
	    delete pV4L;
	}
    }
}

