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

#include <stdio.h>

#include "catalog.h"
#include "item.h"
#include "itemlist.h"
#include "util.h"

#include <qfile.h>
#include <qdir.h>

#include <ksimpleconfig.h>
#include <ktar.h>
#include <kurl.h>

const QSize defTnSize(60,60);

Catalog::Catalog()
   : mLocation(), 
     mItemList( new ItemList()),
     mTnSize(defTnSize)
{
   mDirty = false;
   mNew = true;
   bViewName = true;
   bViewSize = true;
   bViewFilesize = true;
   bViewDesc = false;
   mAddImageDir = QString::null;
}

Catalog::~Catalog()
{
   delete mItemList;
}

void 
Catalog::addItem(Item *newItem)
{
   mItemList->append(newItem);
   newItem->setCatalog(this);
   connect(newItem, SIGNAL(destroyed(Item *)), this, SLOT(removeItem(Item *)));
   emit itemAdded(newItem);
   mDirty = true;
}

void 
Catalog::removeItem(Item *oldItem)
{
   oldItem->setCatalog(0);
   if (mItemList->removeRef(oldItem))
   {
      emit itemRemoved(oldItem);
      mDirty = true;
   }
}

bool 
Catalog::load(const QString &filename)
{
   KTarGz tarFile( filename );

   if ( !tarFile.open(IO_ReadOnly))
   {
      return false;
   }

   const KTarDirectory *tarDir = tarFile.directory();

   QStringList entries = tarDir->entries();

   if (entries.count() != 1)
      return false;

   QString dir = entries.first();

   tarDir = dynamic_cast<const KTarDirectory *>(tarDir->entry(dir));

   if (!tarDir) return false;

   entries = tarDir->entries();

   const KTarFile *infoFile;
   infoFile  = dynamic_cast<const KTarFile *>(tarDir->entry("catalog.info"));
   if (!infoFile) return false;

   QString info = QString::fromUtf8(infoFile->data().data(), infoFile->data().size());
   QStringList infoList = QStringList::split('\n', info);

   int itemCount = 0;

   for(QStringList::Iterator it = infoList.begin();
       it != infoList.end();
       it++)
   {
      QString item = *it;
      if ( match(item, "ThumbNailSize = "))
      {
         QStringList size = QStringList::split(',', item);
         if (size.count() >= 2)
         {
            mTnSize = QSize( size[1].toInt(), size[0].toInt() );
         }
      }
      else if ( match(item, "ItemCount = "))
         itemCount = item.stripWhiteSpace().toInt();
      else if ( match(item, "ViewName = "))
         bViewName = (item[0].lower() == 't');
      else if ( match(item, "ViewSize = "))
         bViewSize = (item[0].lower() == 't');
      else if ( match(item, "ViewFileSize = "))
         bViewFilesize = (item[0].lower() == 't');
      else if ( match(item, "ViewDesc = "))
         bViewDesc = (item[0].lower() == 't');
      else if ( match(item, "AddImageDir = "))
      {
         mAddImageDir = item;
         KURL u(mAddImageDir);
         if (u.isMalformed() || !u.isLocalFile() || !QFile::exists( u.path()))
            mAddImageDir = QDir::homeDirPath();
      }
         
   }

   bool result = false;

   {
   QString info;

   info += QString("ThumbNailSize = %1,%2\n").arg(mTnSize.height()).arg(mTnSize.width());
   info += QString("ItemCount = %1\n").arg(itemCount);
   info += QString("ViewName = %1\n").arg( bViewName ? "true" : "false" );
   info += QString("ViewSize = %1\n").arg( bViewSize ? "true" : "false" );
   info += QString("ViewFileSize = %1\n").arg( bViewFilesize ? "true" : "false" );
   info += QString("ViewDesc = %1\n").arg( bViewDesc ? "true" : "false" );
   info += QString("AddImageDir = %1\n").arg( mAddImageDir );

   fprintf(stderr, "Info:\n%s", info.ascii());
   }

   for( int i = 1; i <= itemCount; i++)
   {
      QString filename;
      filename.sprintf("image%03d", i);

      Item *item = new Item(mTnSize);

      if (!item->loadFrom(tarDir, filename))
      {
          delete item;
          return false;
      }
      addItem(item);      
   }    

   
   return result;
}

bool 
Catalog::save()
{
   QString dir = mLocation;
   KTarGz tarFile( mLocation );

   if ( !tarFile.open(IO_WriteOnly))
   {
      return false;
   }

   int pos = dir.findRev('/');
   if (pos >= 0)   
   {
     dir = dir.mid(pos+1);
   }

   pos = dir.findRev('.');
   if (pos > 0) // We want to have at least 1 remaining character!
   {
     dir = dir.left(pos); 
   }
   QString info;

   info += QString("ThumbNailSize = %1,%2\n").arg(mTnSize.height()).arg(mTnSize.width());
   info += QString("ItemCount = %1\n").arg(mItemList->count());
   info += QString("ViewName = %1\n").arg( bViewName ? "true" : "false" );
   info += QString("ViewSize = %1\n").arg( bViewSize ? "true" : "false" );
   info += QString("ViewFileSize = %1\n").arg( bViewFilesize ? "true" : "false" );
   info += QString("ViewDesc = %1\n").arg( bViewDesc ? "true" : "false" );
   info += QString("AddImageDir = %1\n").arg( mAddImageDir );

   QCString encodedInfo = info.utf8();
   tarFile.writeFile( dir+"/catalog.info", QString::null, QString::null, 
	encodedInfo.length(), encodedInfo);

   int i = 1;
   for( Item *item=mItemList->first(); item; item = mItemList->next(), i++)
   {
      QString filename;
      filename.sprintf("/image%03d", i);
      
      if (!item->saveTo(&tarFile, dir+filename))
          return false;
   }    

   tarFile.close();

   mDirty = false;
   return true;
}

bool 
Catalog::saveAs( QString &filename)
{
   mLocation = filename;
   mNew = false;
   return save();
}

