/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <QtGui>
#include <QStyleFactory>
#include <QSettings>

#include <MvTemplates.h>

#include "MvQApplication.h"
#include "PmContext.h"

MvQApplication::MvQApplication(int& ac, char** av, const char* name) : 
	QApplication(ac,av), MvApplication(ac,av,name)
{
	// Create socket notifier
	// The dataReceived function will be called everytime
	// there is data available in the socket
	int sockfd = getService()->soc;
	sn_ = new QSocketNotifier( sockfd, QSocketNotifier::Read);
	QObject::connect( sn_, SIGNAL(activated(int)),
					this, SLOT(slotDataReceived(int)) );
					
	//Get desktop name
	char *desktop=getenv("MV_DESKTOP_NAME");
	if(desktop == 0)  
	{	
		cout << "Error: MV_DESKTOP_NAME is not defined! MvQApplication exits" << endl;
		exit(1);
	}
	
	string dn(desktop);	
	desktopName_=new char[dn.size()+1];
	desktopName_[dn.size()]='\0';
	memcpy(desktopName_,dn.c_str(),dn.size());
	
	//Get qt style
	char *styleCh=getenv("METVIEW_QT_STYLE");
	if(styleCh == 0)  
	{	
		cout << "Error: METVIEW_QT_STYLE is not defined! MvQApplication exits" << endl;
		exit(1);
	}
	
	QString style(styleCh);
	   
	QStringList styleLst=QStyleFactory::keys();
	if(styleLst.contains(style))
    {
        setStyle(style);
    }

    //---------------------------
    // Set QSettings location
    //---------------------------

    //Set a custom location inside the metview home directory for qsettings
    if(char* spCh=getenv("METVIEW_USER_DIRECTORY"))
    {
        QString sp(spCh);
        sp+="/System/Preferences/._mv_desktop_config_";
        qDebug() << "QSettings path is set to:" << sp;
        QSettings::setPath(QSettings::NativeFormat,QSettings::UserScope,sp);
    }
}

MvQApplication::~MvQApplication()
{
    delete [] desktopName_;
}

void MvQApplication::slotDataReceived(int)
{
	//Disable the notifier
	//Process data from the socket
	//Re-enable the notifier if you are interested in more data
//	const QMetaObject *tt = metaObject ();
//	sn_->setEnabled(false);

	process_service(getService());

//	sn_->setEnabled(true);
}

void MvQApplication::processDropRequest(MvRequest* req)
{
  	send_drop_info(getService(),desktopName_,*req,0);
}
