// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.

#ifndef tools_Qt_session
#define tools_Qt_session

// pure Qt code, no GL.

#include <ostream>
#include <vector>

#include <QtCore/qglobal.h> //For QT_VERSION.
#include <QtCore/qnamespace.h>

#if QT_VERSION < 0x050000
#include <QtGui/qapplication.h>
#include <QtGui/qwidget.h>
#else
#include <QtWidgets/qapplication.h>
#include <QtWidgets/qwidget.h>
#endif

namespace tools {
namespace Qt {

class session {
public:
  session(std::ostream& a_out,int& a_argc,char** a_argv)
  :m_out(a_out)
  ,m_qapp(0)
  ,m_own_qapp(false)
  {
    if(qApp) {
      m_qapp = qApp;
      m_own_qapp = false;
    } else {
      m_qapp = new QApplication(a_argc,a_argv);
      m_own_qapp = true;
    }
  }
  virtual ~session() {
    if(m_own_qapp && m_qapp) delete m_qapp;
    m_qapp = 0;
    m_own_qapp = false;
  }
protected:
  session(const session& a_from)
  :m_out(a_from.m_out)
  ,m_qapp(0)
  ,m_own_qapp(false)
  {}
  session& operator=(const session& a_from){
    if(&a_from==this) return *this;
    return *this;
  }
public:
  std::ostream& out() const {return m_out;}
  bool is_valid() const {return m_qapp?true:false;}
  bool steer() {
    if(!m_qapp) return false;
    m_qapp->exec();
    return true;
  }
  bool sync() {
    if(!m_qapp) return false;
    //m_qapp->exec();
    return true;
  }
public:
  QApplication* qapp() const {return m_qapp;}
  QWidget* create_window(const char* a_title,int a_x,int a_y,unsigned int a_width,unsigned int a_height) {
    if(!m_qapp) return 0;
#ifdef _MSC_VER
    if(a_y<=0) a_y = 60;
#endif
    QWidget* top = new QWidget();
    top->setWindowFlags(::Qt::CustomizeWindowHint
                      | ::Qt::WindowTitleHint
                      | ::Qt::WindowMinMaxButtonsHint
//                    | ::Qt::WindowSystemMenuHint
//		      | ::Qt::WindowFullscreenButtonHint
    );
    top->setGeometry(a_x,a_y,a_width,a_height);
    top->setWindowTitle(s2q(a_title));
  //top->setAttribute(Qt::WA_DeleteOnClose,false);
    return top;
  }
  void delete_window(QWidget* a_window) const {
    if(!m_qapp) return;
    delete a_window;
  }
protected:
  QString s2q(const std::string& a_s) {
#if QT_VERSION < 0x050000
    return QString::fromAscii(a_s.c_str());
#else
    return QString::fromLatin1(a_s.c_str());
#endif
  }
protected:
  std::ostream& m_out;
  QApplication* m_qapp;
  bool m_own_qapp;
};

}}

#endif

