/*
 *   ksame 0.4 - simple Game
 *   Copyright (C) 1997,1998  Marcus Kreutzberger
 * 
 *   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.
 *    
 *   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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <stdio.h>
#include <qkeycode.h>
#include <kapp.h>         
#include <qpainter.h>
#include <qlineedit.h>
#include <qdialog.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qlayout.h>
#include <klocale.h>
#include <kconfig.h>
#include "HighScore.h"


// #define MAX(a,b) ((a)>(b)?(a):(b))

HighScore::HighScore() {
     hs_dlg=0;
     playername[0]=0;
} 
HighScore::~HighScore() {
     if (hs_dlg) delete hs_dlg;
} 


void
HighScore::showScore(bool forceNew) {
    
     if (forceNew&&hs_dlg) {
	  delete hs_dlg;
	  hs_dlg=0;
     }
     
     if (hs_dlg) {
	  hs_dlg->exec();
	  return;
     }
	  
     hs_dlg=new QDialog(0,"Highscore", true);
     
     ASSERT(hs_dlg);

     hs_dlg->setCaption(i18n("Highscores"));
     
     loadScore();
     
     QVBoxLayout *tl = new QVBoxLayout(hs_dlg, 10, 10);
     
     QFont f = hs_dlg->font();
     f.setBold(true);
     int initialsize = f.pointSize();
     int maxtry = 20;
     do {
	  f.setPointSize(f.pointSize()+1);
	  if(--maxtry == 0)
	       break;
     } while(QFontInfo(f).pointSize() != f.pointSize() && 
	     f.pointSize() < initialsize+8);

     QLabel *l = new QLabel(i18n("Highscore"), hs_dlg);
     l->setFont(f);
     l->setMinimumSize(l->sizeHint());
     tl->addWidget(l, 1);
     
     QFrame *frame = new QFrame(hs_dlg);
     frame->setFixedHeight(1);
     frame->setFrameStyle(QFrame::HLine|QFrame::Sunken);
     frame->setLineWidth(1);
     frame->setMidLineWidth(1);
     tl->addWidget(frame, 1);  
     
     QGridLayout *l1 = new QGridLayout(HS_MAXENTRY, 3);
     tl->addLayout(l1, 1);
     l1->addColSpacing(1, 150);
     for(int i = 0; i < HS_MAXENTRY; i++) {
	  QString s = "";
	  s.sprintf("#%d", i+1);
	  l = new QLabel(s, hs_dlg);
	  l->setMinimumSize(l->sizeHint());
	  l1->addWidget(l, i, 0);
	  
	  l = new QLabel(hs_dlg);
	  if(i < hiscore_used)
	       l->setText(hiscore[i].name);
	  l->setMinimumSize(l->sizeHint());
	  l1->addWidget(l, i, 1);
	  
	  s = "";
	  if(i < hiscore_used) 
	       s.sprintf("%5d", hiscore[i].score);
	  l = new QLabel(s, hs_dlg);
	  l->setMinimumSize(l->sizeHint());
	  l1->addWidget(l, i, 2);    
     }
     
     QPushButton *ok=new QPushButton(i18n("Close"),hs_dlg);
     ok->setDefault(true);
     ok->setFocus();
     ok->setFixedSize(ok->sizeHint());
     tl->addWidget(ok,0, QDialog::AlignCenter);
     tl->activate();
     hs_dlg->connect(ok, SIGNAL(clicked()),
		     hs_dlg, SLOT(accept()));

     hs_dlg->exec();
}


void
HighScore::add(int board, int score,int colors) {

     loadScore();
     // Was?? schlechter als der letzte, dann aber raus hier!
     if (hiscore_used&&hiscore_used==HS_MAXENTRY&&score<=hiscore[hiscore_used-1].score) 
	  return;
     // Nach dem Namen fragen

     QDialog dlg(0,i18n("Board"),1);
     QVBoxLayout *tl = new QVBoxLayout(&dlg, 10, 10);
     
    
     QLineEdit *name=new QLineEdit(&dlg,i18n("Name"));
     name->setFocus();
     name->setText(playername.ascii());
     name->selectAll();
     name->setMinimumSize(name->sizeHint());
     
     QLabel *label=new QLabel(name,i18n("Please &enter your name:"),&dlg);

     tl->addWidget(label,0);
     tl->addWidget(name,0);
     tl->addSpacing(10);

     QPushButton *ok=new QPushButton(i18n("OK"),&dlg);
     ok->setDefault(true);
     ok->setFixedSize(ok->sizeHint());
     tl->addWidget(ok,0,QDialog::AlignCenter);
     tl->activate();
     
     dlg.setFixedSize(tl->sizeHint());
     
     dlg.connect(ok, SIGNAL(clicked()), SLOT(accept()));
     dlg.connect(name, SIGNAL(returnPressed()), SLOT(accept()));
     
     if (dlg.exec()) {
	  add(board,score,colors,name->text());
	  showScore(true);
     }
}

void
HighScore::add(int board, int score,int colors,const QString &name) {
     int i;
     
     loadScore();

     QString stripped=name.stripWhiteSpace();

     if (stripped.isEmpty()) 
	  playername=i18n("Anonymous");
     else playername=stripped;

     debug("player: %s",playername.ascii());

     for (i=hiscore_used;i>0;i--) {
	  if (score<=hiscore[i-1].score) break;
	  if (i<HS_MAXENTRY) {
	       hiscore[i]=hiscore[i-1];
	  }
     }
     if (i<HS_MAXENTRY) {
	  hiscore[i].board=board;
	  hiscore[i].score=score;
	  hiscore[i].colors=colors;
	  hiscore[i].name=playername;
	  if (hiscore_used<HS_MAXENTRY) hiscore_used++;
	  storeScore();
     }
}


void
HighScore::loadScore() {
     char cname[17];

     QString name, value;
     KConfig *config = kapp->config();
     
     config->sync();
     QString oldgroup=config->group();
     config->setGroup("Highscore");
     
     hiscore_used=0;
     for (int i=0;i<HS_MAXENTRY;i++) {
	  name.sprintf("Rank_%i",i);
	  if (!config->hasKey(name)) break;
	  // debug("load %i",i);
	  value=config->readEntry(name);
	  memset(cname, 0, 17);
	  if (sscanf(value.data(),"%i %i %i %16c",
		     &hiscore[i].board,
		     &hiscore[i].score,
		     &hiscore[i].colors,
		     cname)!=4) break;
	  cname[16]=0;
	  hiscore[i].name=cname;
	  hiscore_used++;
     }
     playername=config->readEntry("LastPlayer",i18n("Anonymous"));
     debug("lastplayer: %s",playername.ascii());     
     config->setGroup(oldgroup);
}

void
HighScore::storeScore() {
     QString name, value;
     KConfig *config = kapp->config();
     
     QString oldgroup=config->group();
     config->setGroup("Highscore");
     
     for (int i=0;i<hiscore_used;i++) {
	  name.sprintf("Rank_%i",i);
	  value.sprintf("%i %i %i %16s",
			hiscore[i].board,
			hiscore[i].score,
			hiscore[i].colors,
			hiscore[i].name.ascii());
	  config->writeEntry(name, value);
     }
     config->writeEntry("LastPlayer",playername);
     config->setGroup(oldgroup);
     config->sync();
}





