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

#ifndef toolx_Qt_session
#define toolx_Qt_session

// pure Qt code, no GL.

#include "s2q"

#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

#include <ostream>
#include <vector>

namespace toolx {
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;
    }
  }
  session(std::ostream& a_out,QApplication* a_qapp)
  :m_out(a_out)
  ,m_qapp(a_qapp)
  ,m_own_qapp(false)
  {}
  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->processEvents();
    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;
#if defined(_MSC_VER) || defined(__MINGW32__)
    if(a_y<=0) a_y = 60;
#endif
    QWidget* top = new QWidget();
    top->setWindowFlags(::Qt::CustomizeWindowHint
                      | ::Qt::WindowTitleHint
                      | ::Qt::WindowMinMaxButtonsHint
    );
    top->setGeometry(a_x,a_y,a_width,a_height);
    top->setWindowTitle(s2q(a_title));
    return top;
  }
  void delete_window(QWidget* a_window) const {
    if(!m_qapp) return;
    delete a_window;
  }
protected:
  std::ostream& m_out;
  QApplication* m_qapp;
  bool m_own_qapp;
};

}}


#endif

