/***************************************************************************
                          mainwindow.cpp  -  description
                             -------------------
    begin                : Sun Oct 21 2001
    copyright            : (C) 2001 by Primoz Anzur 
    email                : zerokode@gmx.net
        		       (C) 2004 by Reuben Sutton 
    email                : reuben@microsucks.co.uk
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <pwd.h>
#include <time.h>

#include <qdir.h>
#include <qlabel.h>
#include <qimage.h>

#include <kaction.h>
#include <kapplication.h>
#include <kconfigdialog.h>
#include <kdebug.h>
#include <kmenubar.h>
#include <kpopupmenu.h>
#include <kstatusbar.h>

#include "mainwindow.h"
#include "answer.h"
#include "prefs.h"
#include "interface.h"
#include "game.h"

const int IDS_LEVEL      = 100;

MainWindow::MainWindow()
    : KMainWindow( 0, "KMessedWords" ),
      m_view(new KmwView(this))
{
	// tell the KMainWindow that this is indeed the main widget
	setCentralWidget(m_view);
	//connect close of dictionary to new game
	connect(&showConfig, SIGNAL(getClose()), m_view, SLOT(slot_messup()) );
	//config
	config = kapp->config();
	
	setIcon(QPixmap(locate("icon","locolor/16x16/apps/kmessedwords.png")));

	m_setLocalDictionary=locate("data","kmessedwords/");
	QFile f(m_setLocalDictionary+"easy.txt");
	if (! f.exists())
	{
		m_setLocalDictionary=locate("data","kmessedwords/");
	}

	setCaption(i18n ("KMessedWords %1").arg(LOCAL_VERSION));
	check_update();
	// set up the status bar
	statusBar( )->insertItem("   ",IDS_LEVEL, 0);
	connect(m_view, SIGNAL(changeLevel(const QString&)), this, SLOT(updateStatusBar(const QString &)));
	setupActions();
	m_view->setMinimumSize(450, 300); 
	setupGUI();
	loadSettings(); //themeString
}

MainWindow::~MainWindow(){

}

void MainWindow::setupActions()
{
	KStdAction::quit(kapp, SLOT(quit()), actionCollection());
	KAction *m_dictAct = new KAction(i18n("&Dictionary..."), QPixmap(locate("data","kmessedwords/dict.png")), 0, this, SLOT(slot_openBook()),  actionCollection(), "dictionary");
	KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
	levelAct = new KSelectAction(i18n("&Level"), 0, this,  SLOT(slotChangeLevel()), actionCollection(), "level");
	levelAct->setItems(m_view->m_levelString);
	levelAct->setCurrentItem(m_view->m_levelString.findIndex(Prefs::level()));
	KAction *m_playAct = new KAction(i18n("&Play"), QPixmap(locate("data","kmessedwords/play.png")), 0, m_view, SLOT(slot_messup()),  actionCollection(), "play");
	KAction *mScoresAct = new KAction(i18n("&Show Highscores"), "highscore", CTRL+Key_H, m_view, SLOT(slot_scores()),  actionCollection(), "show_highscores");
}

void MainWindow::slot_openBook()
{
	showConfig.show();
}

void MainWindow::slotChangeLevel()
{
	m_view->levelBox->setCurrentItem(levelAct->currentItem());
	//updateStatusBar(m_view->m_levelString[levelAct->currentItem()]);
	m_view->slot_changeLevel(levelAct->currentItem());
}

void MainWindow::check_update()
{
	config->setGroup("Version");
	if (config->readEntry("version","") !="1.0.0")
	{
		for (int i=0; i<=9; i++)
		{
			config->setGroup("Easy_scores");
			config->writeEntry(QString("guesses%1").arg(i),"0");

			config->setGroup("Medium_scores");
			config->writeEntry(QString("guesses%1").arg(i),"0");

			config->setGroup("Hard_scores");
			config->writeEntry(QString("guesses%1").arg(i),"0");
		}
		config->setGroup("Version");
		config->writeEntry("version","1.0.0");
		config->sync();
	}
}

void MainWindow::optionsPreferences()
{
	if ( KConfigDialog::showDialog( "settings" ) )  
		return;
	//KConfigDialog didn't find an instance of this dialog, so lets create it :
	KConfigDialog* dialog = new KConfigDialog( this, "settings",  Prefs::self() );
	interface *mInterface =  new interface( 0, "Interface" );
	mInterface->kcfg_Name->insertStringList(m_themeString);
	dialog->addPage(mInterface, i18n("Interface"), "colorize");
	game *mGame =  new game( 0, "Game" );
	dialog->addPage(mGame, i18n("Game"), "identity");
	connect(dialog, SIGNAL(settingsChanged()), this, SLOT(updateSettings()));
	dialog->show();
	
}

void MainWindow::updateStatusBar(const QString &update)
{
  	statusBar()->changeItem(i18n("Level: %1").arg(update), IDS_LEVEL);
	//this should go elsewhere ideally Set the Level menu after level is changed in ComboBox
	levelAct->setCurrentItem(m_view->levelBox->currentItem());
}


void MainWindow::loadSettings()
{
  	m_view->levelBox->setEnabled(true);
	updateStatusBar(Prefs::level());
	//find the themes
	QDir d(locate("data","kmessedwords/themes/")); //the theme directory...
	d.setFilter( QDir::Dirs);
	d.setSorting( QDir::Name);
		
	for ( unsigned int i=0; i<d.count(); i++ ) {
		if ((d[i] != ".") && (d[i] != "..")) {
			m_themeString.append(d[i]);
		}
  	}
	setBackgroundPic();
	updateButtons();
}

void MainWindow::setBackgroundPic()
{
	//get the themes in the combobox
	QPixmap bgPix;
	QPixmap bg(size());
	m_themeName=m_themeString[Prefs::name()];
	if(Prefs::background())
	{
		bgPix=QPixmap(locate("data","kmessedwords/themes/"+m_themeName+"/kmessedbg.png"));
		QImage img = bgPix.convertToImage();
		bg.convertFromImage(img.smoothScale( m_view->width(), m_view->height()));
		m_view->mainScreen->setPaletteBackgroundPixmap(bg);
	} else {
		m_view->setBackgroundColor("#DCDCDC");
		m_view->mainScreen->setBackgroundColor("#DCDCDC");
	}
}

void MainWindow::resizeEvent(QResizeEvent *)
{
  	if(Prefs::background())
		setBackgroundPic();
}

void MainWindow::updateSettings()
{
  	// This checks this needs changing
	if(Prefs::background())
  	setBackgroundPic();
  	updateButtons();
}

// This function check's the button settings and sets the pictures if necerrsarry
// Added a check to make sure the pictures exist.
void MainWindow::updateButtons()
{
	/*if(Prefs::buttons() && QFile::exists(locate("data","kmessedwords/themes/"+m_themeName+"/btnscore.png"))) {
		updateButtonText();
		m_view->btnScore->setPixmap(QPixmap(locate("data","kmessedwords/themes/"+m_themeName+"/btnscore.png")));
		m_view->btnMess->setPixmap(QPixmap(locate("data","kmessedwords/themes/"+m_themeName+"/btnmess.png")));
		m_view->btnTry->setPixmap(QPixmap(locate("data","kmessedwords/themes/"+m_themeName+"/btntry.png")));
		
	} else 	{*/
		updateButtonText();
/*	}*/
}

void MainWindow::updateButtonText()
{
	m_view->btnScore->setText(i18n("&Scores"));
	m_view->btnMess->setText(i18n("&Play"));
	m_view->btnTry->setText(i18n("&Try"));
	update();
}

#include "mainwindow.moc"




