#include <highscorelist.h>
#include <cstdio>
#include <unistd.h>
#include <algorithm>
#include <qmessagebox.h>

using namespace std;

HighscoreEntry::HighscoreEntry(QString n,int s,int d){
  Name=n;
  Score=s;
  Difficulty=d;
}

HighscoreEntry::HighscoreEntry(){
  Name="";
  Score=0;
  Difficulty=0;
}

bool HighscoreEntry::operator<(HighscoreEntry &b){
  return(Score<b.Score);
}

bool HighscoreEntry::operator==(HighscoreEntry &b){
  return(Score==b.Score);
}

Highscorelist::Highscorelist(){
  readList();
}

Highscorelist::~Highscorelist(){
  writeList();
}

void Highscorelist::readList(char *fname){
  FILE *hfile;
  char *name;
  int score,difficulty;

  hfile=fopen(fname,"r");
  if(!hfile)return;
  while(!feof(hfile)){
    name=new(char[16]);
    fscanf(hfile,"%s %ld %ld",name,&score,&difficulty);
    addToList(QString(name),score,difficulty);
  };
  fclose(hfile);
  sort();
  reverse();
}

void Highscorelist::addToList(QString name,int score,int difficulty){
  insert(end(),HighscoreEntry(name,score,difficulty));
  sort();
  if(size()>10)erase(begin());
  reverse();
}

void Highscorelist::addToList(int score,int difficulty){
  char *envs;
  char *name=0;

  envs=getlogin();
  if(!envs)envs=getenv("USER");
  if(envs){
    addToList(QString(envs),score,difficulty);
  }
}

void Highscorelist::writeList(char *fname){
  FILE *hfile;
  iterator I;

  I=begin();
  hfile=fopen(fname,"w");
  if(!hfile)return;
  while(I!=end()){
    if(I!=begin())fprintf(hfile,"\n");
    fprintf(hfile,"%s %ld %ld",(const char *)(*I).Name,
	    (*I).Score,(*I).Difficulty);
    I++;
  };
  fclose(hfile);
}

void Highscorelist::showList(){
  iterator I;
  char s[1024],*sptr;
  char d[3][8]={"Easy","Normal","Hard"};
  
  // KMsgBox mesg(0,"Highscorelist","This is a test.",1,"Ok",0,0,0);  
  I=begin();
  sptr=s;
  int n=1;
  while(I!=end()){
    sptr+=sprintf(sptr,"%2d %-10s %6d %8s\n",n++,(const char *)((*I).Name)
		  ,(*I).Score,d[(*I).Difficulty]);
    I++;
  };
  QMessageBox::about(0,"KJewels Highscorelist",s);
}
