#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <jewel.h>
#include <qcolor.h>
#include <stream.h>
#include <kstandarddirs.h>
#include <kdebug.h>

QColor Jewel::colorList[8]={
  QColor(255,255,255),
  QColor(255,0,10),
  QColor(0,255,10),
  QColor(0,0,255),
  QColor(255,255,0),
  QColor(0,255,255),
  QColor(255,0,255),
  QColor(200,100,0)
};

Jewel::Jewel(const short p,const short maxcol){
  int i;

  loadPics();
  parts=new(short[p+1]);
  numParts=p;
  maxColors=maxcol;
  xp=3;yp=14;  
  srand((unsigned int)time(0));
  newJewel();
}

int Jewel::loadPics(){

  const QString pics[9]={
    "any_j.png", "red_j.png", "blue_j.png", "green_j.png", "yellow_j.png",
    "malve_j.png", "sea_j.png", "grey_j.png", "muncher.png"
  };

  KStandardDirs kdirs;

  for (int i=0; i<9; i++){
    QString f(kdirs.findResource("data",QString("kjewel/pics/"+pics[i])));
    jewelPixmaps[i]= new QPixmap(f);
    if(!jewelPixmaps[i]){
      kdError() << "Could not load Pixmaps!" << endl;
      return 0;
    }
  }
  return 1;
}

const Jewel &Jewel::operator=(const Jewel &nj)
{
  int i;

  if(parts)delete[](parts);
  parts=new(short[nj.numParts+1]);
  xp=nj.xp;
  yp=nj.yp;
  maxColors=nj.maxColors;
  numParts=nj.numParts;
  for(i=0;i<numParts;i++)parts[i]=nj.parts[i];
  return((const Jewel&)(*this));
}

short Jewel::x(){
  return(xp);
}

short Jewel::y(){
  return(yp);
}

void Jewel::newJewel(){
  int i;

  if(!(rand()%100)){
    for(i=0;i<numParts;i++)parts[i]=10;
    return;
  };
  for(i=0;i<numParts;i++)parts[i]=(rand()%maxColors)+1;
  for(i=0;i<numParts;i++)
    if(!(rand()%100))parts[i]=100;
}

void Jewel::show(QPainter &p){
  int i;
  QBrush br;
  
  p.setPen(Qt::NoPen);
  br.setStyle(Qt::SolidPattern);
  /*  if(parts[0]==10){
    br.setStyle(CrossPattern);
    br.setColor(QColor("white"));
    for(i=0;i<numParts;i++)
      p.fillRect(xp*32+2,32*16-(yp*32+2+i*32),31,31,br);
    return;
  };*/
  for(i=0;i<numParts;i++){
    if(parts[i]<100)
        p.drawPixmap(xp*32+2,32*16-(yp*32+2+i*32)
		     ,*jewelPixmaps[parts[i]==10?8:parts[i]]);
      else{
	p.drawPixmap(xp*32+2,32*16-(yp*32+2+i*32),*jewelPixmaps[0]);
      };
    if(parts[i]==10)
      p.drawPixmap(xp*32+2,32*16-(yp*32+2+i*32),*jewelPixmaps[8]);
    //    p.fillRect(xp*32+2,32*16-(yp*32+2+i*32),31,31,br);
  };
}


void Jewel::step()
{
  yp--;
}
void Jewel::up()
{ 
  int i,h;
  h=parts[numParts-1];
  for (i=numParts-2;i>=0;i--)
    parts[i+1]=parts[i];
  parts[0]=h;
}
void Jewel::down()
{ 
  int h,i;
  h=parts[0];
  for (i=0;i<=numParts-2;i++)
    parts[i]=parts[i+1];
  parts[numParts-1]=h;
}

QRect Jewel::topRect()const{
  QRect rect;

  rect.setY(32*13-((yp-1)*32+2));
  rect.setX(xp*32+2);
  rect.setWidth(32);
  rect.setHeight(32);
  return(rect);
}

QRect Jewel::thisRect()const{
  QRect rect;

  rect.setY(32*13-((yp-1)*32+2));
  rect.setX(xp*32+2);
  rect.setWidth(32);
  rect.setHeight(32*numParts);
  return(rect);
}
