/*
 * Copyright (C) 2001 by Primoz Anzur
		  (C) 2004 Anne-Marie Mahfouf <annma@kde.org>
		(C) 2004 Reuben Sutton <reuben@microsucks.co.uk>
		
    This program is free software; you can redistribute it and/or
    modify it under the terms of version 2 of the GNU General Public
    License as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

//project headers
#include "answer.h"
#include "mainwindow.h"
#include "kmwview.h"
#include "prefs.h"

#include <qlineedit.h>
#include <qlabel.h>

#include <kdebug.h>


KmwView::KmwView(MainWindow *parent, const char *name)
    : FrontEnd(parent, name)
{
	m_guesses=0;
	m_tGuesses=0;
	m_solvedWords=0;
	m_messups=0;
	btnMess->setFocus();	//focus on "Messup" button
	m_levelString.append(i18n("Easy"));
	m_levelString.append(i18n("Medium"));
	m_levelString.append(i18n("Hard"));
	levelBox->insertStringList(m_levelString);
	levelBox->setCurrentItem(m_levelString.findIndex(Prefs::level()));
	connect(btnMess, SIGNAL(clicked()), this, SLOT(slot_messup()));
	connect(btnScore, SIGNAL(clicked()), this, SLOT(slot_scores()));
	connect(btnTry, SIGNAL(clicked()), this, SLOT(slot_try()));
	connect(guessedText, SIGNAL(returnPressed()), this, SLOT(slot_try()));
	connect(levelBox, SIGNAL(activated(int)), this, SLOT(slot_changeLevel(int)));
	//config
	config = kapp->config();
	//mainScreen->setAutoMask(true);
}
    
KmwView::~KmwView()
{
}

void KmwView::slot_try()
{

		if(!guessedText->text().isEmpty())
		{
			m_guesses++;
			m_tGuesses++;

				if(QString::compare(guessedText->text().stripWhiteSpace(),m_cleanWord.stripWhiteSpace())==0)
				{
					kdDebug() << "correct" << endl;
					if (KMessageBox::questionYesNo(this,i18n("Congratulations! You got the right answer after %1 attempts.\n\nPlay again?").arg(m_guesses), "KMessedWords", i18n("Play Again"), i18n("Restart Your Game"))==4)
					{
						//scoring final calc thingy goes here :)
						m_solvedWords++;
						//TODO add this: write_scores();
						QString justtext=i18n("Name: %1\n").arg(Prefs::gamerName()) + i18n("Solved: %1\n").arg(m_solvedWords)+ i18n ("Rounds: %1\n").arg(m_messups);
						KMessageBox::information(this,justtext);
						resetKMW();
						
					}
					else
					{ //here goes on...
						//scoring calc thingy goes here :)
						m_solvedWords++;
						m_guesses=0;
						guessedText->setText("");
						slot_messup();
					}
				}
				else
				{ //if you are wrong...
					kdDebug() << "wrong" << endl;
					KMessageBox::information(this,i18n("Sorry! You got that wrong! Try again!"), "KMessedWords"); //this should be replaced by a graphical box [?]
					guessedText->setText("");
				}
		}
}

void KmwView::slot_scores()
{
	m_showScores.show(); //much better solution... It shows only one instance of the window...
}

void KmwView::slot_messup()
{
	// enable Buttons on first button click
	if (!guessedText->isEnabled())
	{
		guessedText->setEnabled(true);
		txtGuess->setEnabled(true);
		btnTry->setEnabled(true);
		btnMess->setDefault(false);
	}
	randomizer(levelBox->currentItem());
	messWord();

	//prevents clean words to be displayed...
	if (m_cleanWord.stripWhiteSpace()==m_messedWord.stripWhiteSpace())
	{
		slot_messup();
		//m_messups ++;  //this is for nothing more than monitoring the completenumbers of messed and clean words...
	}
	else
	{
		m_messups++;
		mainScreen->setText(m_messedWord.stripWhiteSpace());
		guessedText->setFocus();
	}
}

void KmwView::randomizer(int level)
{
	reloadStructure();
	if(level==0)
	{
		m_lines=configInputData.easyDict->numLines();
		m_cleanWord=configInputData.easyDict->textLine( m_random.getLong(m_lines) ).stripWhiteSpace();
	}
	if(level==1)
	{
		m_lines=configInputData.mediumDict->numLines();
		m_cleanWord=configInputData.mediumDict->textLine( m_random.getLong(m_lines) ).stripWhiteSpace();
	}
	if(level==2)
	{
		m_lines=configInputData.hardDict->numLines();
		m_cleanWord=configInputData.hardDict->textLine( m_random.getLong(m_lines) ).stripWhiteSpace();
	}
}

void KmwView::messWord()
{
	QPtrList <QChar> messList;
	messList.setAutoDelete(true);
	
		// Put all letters of the word in the list
	for(unsigned int i = 0; i < m_cleanWord.length(); i++)
	{
		messList.append(new QChar( m_cleanWord[i] ));
	}
	
		// Shuffle the list
	m_random.randomize(&messList);
	
		// Give the messed up string the right length.
	m_messedWord.fill(' ', m_cleanWord.length());
	
		// Copy all letters to the messed u-p string.
	for(unsigned int i = 0; i < m_cleanWord.length(); i++)
	{
		m_messedWord[i] = *(messList.at(i));
	}
}

void KmwView::reloadStructure(){
	//this too is a-must-have for the paths and file checkings and stuff...
	QString setLocalDictionary=locate("data","kmessedwords/"); //<-this NEEDS to be there due to the info, that is in the Locate path [graphics and files]
	QFile f(setLocalDictionary+"easy.txt");
	if (! f.exists())
	{
	setLocalDictionary=locate("data","kmessedwords/");
	}
	
		//this is just a patch.. It reloads the files into the dictionary buffer...
	QFile openEasyFile(setLocalDictionary+"easy.txt");
	openEasyFile.open(IO_ReadOnly);
	QTextStream readEasyStr(&openEasyFile);
	configInputData.easyDict->setText(readEasyStr.read().stripWhiteSpace());
	openEasyFile.close();
	
	QFile openMediumFile(setLocalDictionary+"medium.txt");
	openMediumFile.open(IO_ReadOnly);
	QTextStream readMediumStr(&openMediumFile);
	configInputData.mediumDict->setText(readMediumStr.read().stripWhiteSpace());
	openMediumFile.close();
	
	QFile openHardFile(setLocalDictionary+"hard.txt");
	openHardFile.open(IO_ReadOnly);
	QTextStream readHardStr(&openHardFile);
	configInputData.hardDict->setText(readHardStr.read().stripWhiteSpace());
	openHardFile.close();
}

void KmwView::slot_changeLevel(int id)
{
	resetKMW();
	btnMess->setDefault(true);
	Prefs::setLevel(m_levelString[id]);
	Prefs::writeConfig();
	emit changeLevel(m_levelString[id]);
}

void KmwView::resetKMW()
{
	m_messups=0;
	m_solvedWords=0;
	m_guesses=0;
	m_tGuesses=0;
	guessedText->setText("");
	mainScreen->setText("KMessedWords");
	guessedText->setEnabled(false);
	guessedText->setEnabled(false);
	txtGuess->setEnabled(false);
	btnTry->setEnabled(false);
}

void KmwView::slotEnd()
{
	m_solvedWords++;
	write_scores();
	QString justtext=i18n("Name: %1\n").arg(Prefs::gamerName()) + i18n("Solved: %1\n").arg(m_solvedWords)
	+ i18n ("Rounds: %1\n").arg(m_messups);
	KMessageBox::information(this, justtext);
	kapp->quit();
}

void KmwView::slotReply()
{
	m_solvedWords++;
	m_guesses=0;
	guessedText->setText("");
	slot_messup();
}

void KmwView::write_scores()
{
		//this is for the levels...
	if (levelBox->currentItem()==0)
		config->setGroup("Easy_scores");
	else if (levelBox->currentItem()==1)
		config->setGroup("Medium_scores");
	else
		config->setGroup("Hard_scores");
	
	int rank = 10;
	int j = 0;
	for (int i=0; j<=9; i++,j++) //we load everything in cache
	{
		m_readName[j]=config->readEntry(QString("name%1").arg(i),"Anonymous");
		m_readSolved[j]=config->readNumEntry(QString("solved%1").arg(i),0);
		m_readRounds[j]=config->readNumEntry(QString("rounds%1").arg(i),0);
		m_readGuesses[j]=config->readNumEntry(QString("m_guesses%1").arg(i),0);
		if ((rank > i) && (m_readSolved[i] < m_solvedWords))
		{
			// Insert new score here.
			rank = i;
			j++;
			if (j <= 9)
			{
				m_readName[j] = m_readName[i];
				m_readSolved[j] = m_readSolved[i];
				m_readRounds[j] = m_readRounds[i];
				m_readGuesses[j] = m_readGuesses[i];
			}
			m_readName[i] = Prefs::gamerName();
			m_readSolved[i] = m_solvedWords;
			m_readRounds[i] = m_messups;
			m_readGuesses[i] = m_tGuesses;
		}
	}
	
	qWarning("Rank = %d", rank);
	if (rank > 9)
		return;
	
	for (int x=0;  x<=9; x++) // write back all scores
	{
		config->writeEntry(QString("name%1").arg(x), m_readName[x]);
		config->writeEntry(QString("solved%1").arg(x),m_readSolved[x]);
		config->writeEntry(QString("rounds%1").arg(x),m_readRounds[x]);
		config->writeEntry(QString("m_guesses%1").arg(x),m_readGuesses[x]);
	}
	config->sync();
}

#include  "kmwview.moc"
