#include "gamewidget.h"

#include "gamescene.h"
#include "gamesound.h"
#include "gameprofile.h"
#include "gamemenu.h"

#include "displaywrapper.h"

QString GameWidget::resourcePath;

GameWidget::GameWidget(QWidget *parent)
    : QGraphicsView(parent)
{
  qsrand(QTime::currentTime().msec());

#ifdef Q_OS_WIN32
  resourcePath = QApplication::applicationDirPath();
  resourcePath.chop(3);
  resourcePath += "data/"; // bin -> data
#else
  resourcePath = "/usr/local/games/jag/data/";
#endif

  setSceneRect(1, 1, 1022, 766);

  // create sound engine
  sndEngine = new GameSound();
  connect(sndEngine, SIGNAL(musicFinished()), this, SLOT(playRandomMusic()));


  // create and load profile
  gameProfile = new GameProfile(this);
  gameProfile->loadProfile();


  // play music if enabled
  playRandomMusic();


  // create and setup scene

  // use acceleration
  if (gameProfile->isAccelerated())
    setViewport(new QGLWidget());

  setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);

  setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

  scene = new GameScene(this);
  setScene(scene);


  // setup window
  connect(scene->gameMenu(), SIGNAL(menuVideoModeChanged()),
          this, SLOT(setVideoMode()));

  resize(1024,768);
  setVideoMode();
}

GameWidget::~GameWidget()
{
  gameProfile->saveProfile();

  delete sndEngine;
  delete gameProfile;

  QApplication::quit();
}

void GameWidget::closeEvent(QCloseEvent *event)
{
    if (!scene->confirmExit())
        event->ignore();
}

void GameWidget::drawBackground ( QPainter * painter, const QRectF & rect )
{
  painter->fillRect(rect, Qt::black);

  scene->drawBackground(painter, rect);
}

void GameWidget::keyPressEvent ( QKeyEvent * keyEvent )
{
  scene->keyPressEvent(keyEvent);
}

void GameWidget::focusOutEvent ( QFocusEvent * event )
{
  QWidget::focusOutEvent(event);

  scene->pauseGame();
}

void GameWidget::setVideoMode()
{
  showNormal();

  QApplication::processEvents();

  if (gameProfile->isFullscreen())
  {
    // set full screen mode
    if (!DisplayWrapper::switchVideoMode(1024,768,0,true))
    {
      qDebug() << "Unable to change resolution.";
    }

    showFullScreen();
  }
  else
  {
    DisplayWrapper::restoreVideoMode();

    resize(1024,768);
    move(0,0);
    setMinimumSize(1024, 768);

    if (gameProfile->isWindowed())
      showFullScreen();
    else
      showNormal();
  }
}

void GameWidget::playRandomMusic()
{
  QStringList ext; ext << "*.mp3" << "*.wav" << "*.mod";
  QString path(resourcePath + "/music");
  QStringList entryList = QDir(path).entryList(ext);
//  qDebug() << entryList;
  if (entryList.count())
  {
    int r = qrand() % entryList.count();
//    qDebug() << path + "/" + entryList.at(r);
    sndEngine->loadMusic(path + "/" + entryList.at(r));
    sndEngine->playMusic();
  }
}
