#include <qimage.h>
#include <qbitmap.h>
#include <qpainter.h>
#include <qiconview.h>
#include <qdragobject.h>
#include <qmessagebox.h>

#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>

#include "iconview.h"

IconView::IconView(QWidget * parent,const char * name,WFlags f)
  : QTableView(parent,name,f)
{
  setTableFlags(Tbl_autoScrollBars);
  setAcceptDrops(TRUE);
  xsize=0;
  ysize=0;
  setNumRows(20);
  setNumCols(2);
  setCellHeight(50);
  elements.resize(20);
  zero();  
}

void IconView::zero()
{
  // Zero out elements
  unsigned int loopc;
  for(loopc=0;loopc<elements.size();loopc++) {
    elements[loopc]=new IconElement();
  }
}

void IconView::paintCell(QPainter * p,int row,int column)
{
  IconElement * ie;
  ie=elements[row];
  if(column==0) {
    if(ie->pixmap) {
      if(!ie->pixmap->isNull()) {
        p->drawPixmap(5,5,*(ie->pixmap));
      }
    } else {
      p->drawRect(5,5,xsize,ysize);
    }
  } else {
    if(row<(signed int)elements.size()) {
      QString tmp=ie->name;
      p->drawText(5,5,500,ysize,AlignLeft | AlignVCenter | DontClip,tmp);
    }
  }
}

void IconView::mousePressEvent(QMouseEvent * qme)
{
  int thex,they;
  thex=findCol(qme->x());
  they=findRow(qme->y());
  if(qme->button()==LeftButton) {
    KURL url = KFileDialog::getOpenURL();
    
    if( url.isEmpty() )
      return;

    if( !url.isLocalFile() )
    {
      KMessageBox::sorry( 0L, i18n( "Only local files are supported yet." ) );
      return;
    }
    
    QString fn = url.path();
    load_file(fn,they);
  } else {
    IconElement * ie;
    ie=elements[they];
    if(ie->pixmap) {
      delete ie->pixmap;
      ie->pixmap=0;
    }
    ie->name="<unassigned>";
    update();
  }
}

int IconView::cellWidth(int col)
{
  if(col==0) {
    return 50;
  } else {
    return width()-(xsize+10);
  }
}

void IconView::dragEnterEvent(QDragEnterEvent * event)
{
  printf("Drag enter\n");
  if(QIconDrag::canDecode(event)) {
    printf("Can decode\n");
  }
  event->accept(QIconDrag::canDecode(event));
}

void IconView::load_file(QString fn,int they)
{
  if(they<0) {
    they=-1;
  }

  printf("They at load_file %d\n",they);
  QString thename;
  QString f2=fn;
  int i;
  printf("%s\n",f2.ascii());
  i=f2.findRev('/');
  if(i>-1) {
    printf("Removing %d\n",i);
    f2=f2.remove(0,i+1);
  }
  printf("%s",f2.ascii());
  i=f2.find('.');
  if(i>-1) {
    f2=f2.remove(i,f2.length()-i);
  }
  thename=f2;

  printf("Load for %s %d %d\n",fn.ascii(),they,elements.size());
  if(they>0) {
    if(they>(signed int)elements.size()) {
      // User clicked outside of area
      printf("Returning\n");
      return;
    }
  }
  printf("Not returning\n");
  bool found=false;
  if(they==-1) {
    for(int loopc=0;loopc<(signed int)elements.size();loopc++) {
      if(elements[loopc]->name=="<unassigned>") {
        printf("Found unassigned\n");
        they=loopc;
        loopc=elements.size()+1;
        found=true;
      }
      if(elements[loopc]->name==thename) {
        delete elements[loopc]->pixmap;
        they=loopc;
        loopc=elements.size()+1;
        found=true;
      }
    }
  }
  printf("Done loop\n");
  if(!found && they==-1) {
    printf("Need to resize to %d\n",elements.size()+1);
    if(!elements.resize(elements.size()+1)) {
      printf("Couldn't resize!\n");
    } else {
      printf("Resized, size now %d\n",elements.size());
      setNumRows(elements.size());
      updateTableSize();
    }
    elements[elements.size()-1]=new IconElement();
    they=elements.size()-1;
  }
  printf("They %d\n",they);
  fn.stripWhiteSpace();
  printf("Pixmap load [%s]\n",fn.ascii());
  QPixmap * qfp=new QPixmap();
  if(!qfp->load(fn)) {
    printf("Load error for [%s]\n",fn.ascii());
  }
  if(xsize==0 && ysize==0) {
    xsize=qfp->width();
    ysize=qfp->height();
  } else {
    if(qfp->width()!=xsize || qfp->height()!=ysize) {
      printf("Size return %d %d, %d %d\n",xsize,ysize,qfp->width(),
              qfp->height());
      return;
    }
  }
  if(!qfp->isNull()) { 
    printf("Loaded %s into %d\n",fn.ascii(),they);
    elements[they]->pixmap=new QPixmap(fn);
    elements[they]->name=thename;
    update();
  } else {
    printf("Couldn't load [%s]!\n",fn.ascii());
    elements[they]->pixmap=0;
    elements[they]->name="<unassigned>";
  }
}

void IconView::load_index(QString stubname)
{
  QString imgname=stubname+".xpm";
  QString indname=stubname+".ind";
  QPixmap p(imgname);
  p.setMask(p.createHeuristicMask());
  if(p.isNull()) {
    return;
  }
  xsize=p.height();
  ysize=p.height();
  printf("Size %d %d, depth %d\n",xsize,ysize,p.depth());
  FILE * f=fopen(indname.ascii(),"r");
  if(!f) {
    printf("Couldn't open file\n");
    return;
  }
  char buf[300];
  char buf2[300];
  int they;
  int countit=0;
  unsigned int loopc;
  for(loopc=0;loopc<elements.size();loopc++) {
    if(elements[loopc]->pixmap) {
      delete elements[loopc]->pixmap;
    }
    elements[loopc]->name="<unassigned>";
  }
  while(fgets(buf,300,f)) {
    sscanf(buf,"%d %s",&they,buf2);
    if(they>countit)
      countit=they;
    if((they+1)>((signed)elements.size())) {
      printf("Need resize %d\n",they);
      if(!elements.resize(they+1)) {
        printf("failed\n");
        return;
      }
      elements[they]=new IconElement();
    }
    QPixmap * p2=new QPixmap(xsize,ysize,p.depth());
    p2->fill();
    bitBlt(p2,0,0,&p,they*xsize,0,xsize,ysize,CopyROP,false);
    p2->setMask(p2->createHeuristicMask());
    elements[they]->pixmap=p2;
    elements[they]->name=QString(buf2);
  }
  if((signed)elements.size()>(countit+1)) {
    elements.truncate(countit+1);
  }
  setNumRows(countit+1);
  updateTableSize();
  update();
}

void IconView::load_files(QString files)
{
  if(files.isNull()) {
    printf("load_files with null string!\n");
    return;
  }
  printf("load_files [%s]\n",files.ascii());
  QString thefile;
  int pos=files.find('\n');
  if(pos==-1) {
    thefile=files;
    printf("No carriage return, [%s]\n",thefile.ascii());
    thefile=thefile.stripWhiteSpace();
    printf("Result [%s]",thefile.ascii());
    if(thefile.left(6)=="file:/") {
      printf("Is a file\n");
      load_file(thefile.mid(5),-1);
    } else {
      printf("Not a file\n");
    }
    printf("About to return\n");
    return;
  }
  while(pos!=-1) {
    printf("Pos was %d\n",pos);
    thefile=files.left(pos);
    files=files.mid(pos+1);
    printf("%s\n",thefile.ascii());
    thefile=thefile.stripWhiteSpace();
    if(thefile.left(6)=="file:/") {
      load_file(thefile.mid(5),-1);
    }
    pos=files.find('\n');
  }
}

void IconView::save(QString stubname)
{
  QString pixname=stubname+".xpm";
  QString indexname=stubname+".ind";
  int countit=0;
  unsigned int loopc;
  int thedepth=1;
  for(loopc=0;loopc<elements.size();loopc++) {
    if(elements[loopc]->name!="<unassigned>" && elements[loopc]->pixmap) {
      countit++;
      if(elements[loopc]->pixmap->depth()>thedepth)
        thedepth=elements[loopc]->pixmap->depth();
    }
  }
  QPixmap p(xsize*countit,ysize,thedepth);
  p.fill();
  countit=0;
  FILE * f=fopen(indexname.ascii(),"w");
  if(!f) {
    QMessageBox::critical(this,"Couldn't save file",
                          "Cannot create index file "+indexname,"Ok");
    return;
  }
  char buf[300];
  for(loopc=0;loopc<elements.size();loopc++) {
    if(elements[loopc]->name!="<unassigned>" && elements[loopc]->pixmap) {
      bitBlt(&p,countit*xsize,0,elements[loopc]->pixmap,0,0,
             xsize,ysize);
      if(elements[loopc]->name.length()<300) {
        strcpy(buf,elements[loopc]->name.ascii());
        fprintf(f,"%d %s\n",countit,buf);
      } else {
        QMessageBox::critical(this,"Name too long",
                              "Icon names have to be less than 300 characters",
                              "Ok");
      }
      countit++;
    }
  }
  fclose(f);
  p.setMask(p.createHeuristicMask());
  if(!p.save(pixname,"XPM")) {
      QMessageBox::critical(this,"Unable to save images",
                            "Couldn't save image file "+pixname,
                            "Ok");
  }  
}

void IconView::do_new()
{
  unsigned int loopc;
  for(loopc=0;loopc<elements.size();loopc++) {
    if(elements[loopc]->pixmap) {
      delete elements[loopc]->pixmap;
      elements[loopc]->pixmap=0;
    }
    elements[loopc]->name="<unassigned>";
  }
  xsize=0;
  ysize=0;
  update();
}

void IconView::dropEvent(QDropEvent * event)
{
  printf("Drop\n");
    QByteArray ba = event->encodedData( "text/uri-list" );
    if ( ba.size() ) {
	uint c = 0;
	char* d = ba.data();
	while ( c < ba.size() ) {
	    uint f = c;
	    while ( c < ba.size() && d[ c ] )
		c++;
	    if ( c < ba.size() ) {
                printf(">>%s\n",( d + f ));
                QString tmp;
                char * zoogle=(d+f);
                tmp=zoogle;
                load_files(tmp);
		c++;
	    } else {
		QString s( QString(d + f).left(c - f + 1) );
		printf("<<[%s]\n",( s ).ascii());
                load_files(s);
	    }
	}
	return;
    }
}
