/*
 * item.cpp. 
 *
 * Copyright (C) 1999 Waldo Bastian
 *
 */

#include <qfile.h>
#include <qimage.h>
#include <qfile.h>
#include <qdatastream.h>
#include <qcstring.h>
#include <qbuffer.h>

#include <klocale.h>
#include <ktar.h>

#include "item.h"
#include "util.h"

Item::Item(QSize tnSize)
  : mTnImg(), mSize(0), mTnSize(tnSize)
{
   mLoadOk = false;
   mImg = 0;
   mCat = 0;
}

Item::Item(const QString &path)
{
printf("File =\"%s\"", path.ascii());
   mLoadOk = false;
   mImg = 0;
   mCat = 0;

   QFile f(path);
   if (!f.open( IO_ReadOnly))
       return;

   Q_INT8 internalImg;

   QDataStream s( &f );
   s >> mComment;
   s >> mKeywords;
   s >> mLocation;
   s >> mSize;
   s >> mDimensions;
   s >> internalImg;
   f.close();

   if (internalImg)
   {
      mImg = new QImage();
      if (!mImg->load(path+".img.png"))
         return;
   }

   if (!mTnImg.load(path+".png"))
      return;
   mLoadOk = (f.status() == IO_Ok);
}

Item::~Item()
{
   emit destroyed(this);
   delete mImg;
}

QString 
Item::name()
{ 
   if (mImg)
      return mLocation;

   KURL url = mLocation; 
   return url.filename(); 
}


bool
Item::loadImage(const KURL &location)
{
   if (!location.isLocalFile())  
   {
printf("URL is not a local file.\n");
      return false;
   }

   QFile file(location.path());

   if (!file.exists())
   {
printf("File does not exists (%s).\n", location.path().ascii());
      return false;
   }
   mSize = file.size();  
 

   QImage img(location.path());

   if (img.isNull())
   {
printf("Error loading image (%s).\n", location.path().ascii());
      return false;
   }

   mLocation = location.url();
   mDimensions = img.size();

   QSize newSize = mDimensions;

   if (newSize.width() > mTnSize.width())
   {
       newSize.setHeight((newSize.height()* mTnSize.width()) / newSize.width());
       newSize.setWidth(mTnSize.width());
   }

   if (newSize.height() > mTnSize.height())
   {
       newSize.setWidth((newSize.width()* mTnSize.height()) / newSize.height());
       newSize.setHeight(mTnSize.height());
   }

   mTn = img.smoothScale(newSize.width(), newSize.height());
   return true;
}

bool
Item::setImage(const QImage &img)
{
   mImg = new QImage(img);
   mSize = 0;  

   if (img.isNull())
   {
printf("Invalid image.\n");
      return false;
   }

   mLocation = "<Image>";
   mDimensions = img.size();

   QSize newSize = mDimensions;

   if (newSize.width() > mTnSize.width())
   {
       newSize.setHeight((newSize.height()* mTnSize.width()) / newSize.width());
       newSize.setWidth(mTnSize.width());
   }

   if (newSize.height() > mTnSize.height())
   {
       newSize.setWidth((newSize.width()* mTnSize.height()) / newSize.height());
       newSize.setHeight(mTnSize.height());
   }

   mTnImg = img.smoothScale(newSize.width(), newSize.height());
   return true;
}

bool 
Item::saveTo(KTarGz *tarFile, const QString &path)
{
printf("Saving to %s\n", path.ascii());
   
   QString info;
   
   info += QString("Comment = %1\n").arg( mComment);
   info += QString("Keywords = %1\n").arg( mKeywords );
   info += QString("Location = %1\n").arg( mLocation );
   info += QString("Size = %1\n").arg( mSize );
   info += QString("Dimensions = %1,%2\n").arg( mDimensions.height()).arg(mDimensions.width());

   QCString encodedInfo = info.utf8();
   tarFile->writeFile( path+".info", QString::null, QString::null, 
	encodedInfo.length(), encodedInfo);

   QByteArray a;
   QBuffer s(a);
   s.open(IO_WriteOnly);
   QImageIO io;
  
   io.setImage(mTn.convertToImage());
   io.setIODevice(&s);
   io.setFormat("PNG");
   io.write();  

   s.close();

   tarFile->writeFile( path+".png", QString::null, QString::null,
        a.size(), a);

   return true;
}

bool 
Item::loadFrom(const KTarDirectory *tarDir, const QString &path)
{
   QString filename = path+".info"; 
printf("Loading %s\n", filename.ascii());

   const KTarFile *infoFile;
   infoFile  = dynamic_cast<const KTarFile *>(tarDir->entry(filename));
   if (!infoFile) 
   {
      fprintf(stderr, "Error loading file: missing '%s'\n", filename.ascii());
      return false;
   }
   const QByteArray infoData = infoFile->data();
   QString info = QString::fromUtf8( infoData.data(), infoData.size());
   QStringList infoList = QStringList::split('\n', info);

   for(QStringList::Iterator it = infoList.begin();
       it != infoList.end();
       it++)
   {
      QString item = *it;
      if ( match(item, "Comment = "))
         mComment = item;
      else if ( match(item, "Keywords = "))
         mKeywords = item;
      else if ( match(item, "Location = "))
         mLocation = item.stripWhiteSpace();
      else if ( match(item, "Size = "))
         mSize = item.stripWhiteSpace().toInt();
      else if ( match(item, "Dimensions = "))
      {
         QStringList size = QStringList::split(',', item);
         if (size.count() >= 2)
         {
            mDimensions = QSize( size[1].toInt(), size[0].toInt() );
         }
      }
   }

   filename = path+".png"; 
printf("Loading %s\n", filename.ascii());

   const KTarFile *imageFile;
   imageFile  = dynamic_cast<const KTarFile *>(tarDir->entry(filename));
   if (!imageFile) 
   {
      fprintf(stderr, "Error loading file: missing '%s'\n", filename.ascii());
      return false;
   }
   const QByteArray imgData = imageFile->data();
   mTnImg.loadFromData((const uchar *) imgData.data(), imgData.size());

   mLoadOk = true;
   return true;
}
