/***************************************************************************
 *   Copyright (C) by                                                      *
 *     - 2005: Christian Leh <moodwrod@web.de>                             *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <kuser.h>
#include <kstandarddirs.h>
#include <kconfig.h>

#include <qfileinfo.h>
#include <qdatetime.h>
#include <qimage.h>

#include "cache.h"

Cache::Cache(Scaler* scaler, const QString& themeEngine, const QString& theme)
{
  mScaler = scaler;
  mTheme = theme;
  mThemeEngine = themeEngine;

  if (mScaler->resolutionDiff())
    createCacheDir();
}


QImage* Cache::cacheFile(const QString& file)
{
  // file must be the full path to queried image so that we can return
  // a new instance if no cached version exists
  QStringList parts = QStringList::split("/", file);
  QFile cachedFile(mCacheDir.filePath(parts.last()));

  if (!mScaler->resolutionDiff())
    return new QImage(file);
  else if (isInSync(parts.last()) && cachedFile.exists())
    return new QImage(cachedFile.name());
  else
  {
    QImage *i = new QImage(file);
    
    // update cache if image needs to be scaled (base != target)
    if (mScaler->scaleSize(i))
      i->save(cachedFile.name(), QImage::imageFormat(file));

    writeInfoFile(parts.last());

    return i;
  }
}


void Cache::createCacheDir()
{
  KUser user;
  QString path = user.homeDir() + "/.kde/" + KStandardDirs::kde_default("data");
  path += QString("ksplash/cache/%1/%2/%3x%4").arg(mThemeEngine).arg(mTheme).arg(mScaler->targetResolution().width()).arg(mScaler->targetResolution().height()) + "/";

  mCacheDir.setPath(path);

  QDir d(mCacheDir.path());

  if (!d.exists())
  {
    QStringList parts = QStringList::split("/", mCacheDir.path());
    QString tmp;

    for (int i = 0; i < parts.count(); i++)
    {
      tmp += "/" + parts[i];
      d = tmp;
      d.mkdir(tmp);
    }
  }
}


void Cache::writeInfoFile(QString& file)
{
  QFileInfo fi(getFile(file));

  KConfig cfg(getFile("info"));
  cfg.setGroup("Cached");
  cfg.writeEntry(file, fi.lastModified());
}


bool Cache::isInSync(QString& file)
{
  QFileInfo fi(getFile(file));

  KConfig cfg(getFile("info"));
  cfg.setGroup("Cached");
  QDateTime dt = cfg.readDateTimeEntry(file);
  
  return (fi.lastModified() == dt);
}


QString Cache::getFile(QString file)
{
  return mCacheDir.filePath(file);
}
