/* ============================================================
 *
 * This file is a part of kipi-plugins project
 * http://www.kipi-plugins.org
 *
 * Date        : 2003-12-03
 * Description : misc utils to used in batch process
 * 
 * Copyright (C) 2003-2005 by Renchi Raju <renchi@pooh.tam.uiuc.edu>
 * Copyright (C) 2004-2007 by Marcel Wiesweg <marcel dot wiesweg at gmx dot de>
 * Copyright (C) 2006-2007 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * NOTE: Do not use kdDebug() in this implementation because 
 *       it will be multithreaded. Use tqDebug() instead. 
 *       See B.K.O #133026 for details.
 *
 * 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, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * ============================================================ */

// C Ansi includes.

extern "C" 
{
#include <sys/types.h>
#include <sys/stat.h>
#include <utime.h>
#include <unistd.h>
}

// TQt includes.

#include <tqfileinfo.h>
#include <tqimage.h>
#include <tqstring.h>
#include <tqfile.h>
#include <tqdir.h>

// KDE includes.

#include <tdetempfile.h>
#include <kprocess.h>
#include <tdelocale.h>
#include <kurl.h>

// LibKExiv2 includes. 

#include <libkexiv2/kexiv2.h>

// LibKDcraw includes.

#include <libkdcraw/version.h>
#include <libkdcraw/kdcraw.h>

#if KDCRAW_VERSION < 0x000106
#include <libkdcraw/dcrawbinary.h>
#endif

// Local includes.

#include "pluginsversion.h"
#include "utils.h"
#include "utils.moc"

namespace KIPIJPEGLossLessPlugin
{

Utils::Utils(TQObject *parent)
     : TQObject(parent)
{
}

Utils::~Utils()
{
}

bool Utils::updateMetadataImageMagick(const TQString& src, TQString& err)
{
    TQFileInfo finfo(src);
    if (src.isEmpty() || !finfo.isReadable())
    {
        err = i18n("unable to open source file");
        return false;
    }

    TQImage img(src);
    TQImage iptcPreview   = img.scale(1280, 1024, TQImage::ScaleMin);
    TQImage exifThumbnail = iptcPreview.scale(160, 120, TQImage::ScaleMin);

    KExiv2Iface::KExiv2 meta;
    meta.load(src);
    meta.setImageOrientation(KExiv2Iface::KExiv2::ORIENTATION_NORMAL);
    meta.setImageProgramId(TQString("Kipi-plugins"), TQString(kipiplugins_version));
    meta.setImageDimensions(img.size());
    meta.setExifThumbnail(exifThumbnail);
    meta.setImagePreview(iptcPreview);
    TQByteArray ba = meta.getExif();
    const uchar exifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
    TQByteArray exifData = TQByteArray(ba.size() + sizeof(exifHeader));
    memcpy(exifData.data(), exifHeader, sizeof(exifHeader));
    memcpy(exifData.data()+sizeof(exifHeader), ba.data(), ba.size());
    TQByteArray iptcData = meta.getIptc(true);

    KTempFile exifTemp(TQString(), "kipipluginsiptc.app1");
    exifTemp.setAutoDelete(true);
    TQFile *exifFile = exifTemp.file();
    if ( !exifFile )
    {
        err = i18n("unable to open temp file");
        return false;
    }
    TQDataStream streamExif( exifFile );
    streamExif.writeRawBytes(exifData.data(), exifData.size());
    exifFile->close();

    KTempFile iptcTemp(TQString(), "kipipluginsiptc.8bim");
    iptcTemp.setAutoDelete(true);
    TQFile *iptcFile = iptcTemp.file();
    if ( !iptcFile )
    {
        err = i18n("Cannot rotate: unable to open temp file");
        return false;
    }
    TQDataStream streamIptc( iptcFile );
    streamIptc.writeRawBytes(iptcData.data(), iptcData.size());
    iptcFile->close();

    TDEProcess process;
    process.clearArguments();
    process << "mogrify";
    process << "-verbose";

    process << "-profile";
    process << exifTemp.name();

    process << "-profile";
    process << iptcTemp.name();

    process << src + TQString("[0]");

    tqDebug("ImageMagick Command line args:");
    TQValueList<TQCString> args = process.args();
    for (TQValueList<TQCString>::iterator it = args.begin(); it != args.end(); ++it)
        tqDebug("%s", (const char*)(*it));

    connect(&process, TQ_SIGNAL(receivedStderr(TDEProcess *, char*, int)),
            this, TQ_SLOT(slotReadStderr(TDEProcess*, char*, int)));

    if (!process.start(TDEProcess::Block, TDEProcess::Stderr))
        return false;

    if (!process.normalExit())
        return false;

    switch (process.exitStatus())
    {
        case 0:  // Process finished successfully !
        {
            return true;
            break;
        }
        case 15: //  process aborted !
        {
            return false;
            break;
        }
    }

    // Processing error !
    err = i18n("Cannot update metadata: %1").arg(m_stdErr.replace('\n', ' '));
    return false;
}

void Utils::slotReadStderr(TDEProcess*, char* buffer, int buflen)
{
    m_stdErr.append(TQString::fromLocal8Bit(buffer, buflen));
}

bool Utils::isJPEG(const TQString& file)
{
    TQString format = TQString(TQImageIO::imageFormat(file)).upper();
    return format=="JPEG";
}

bool Utils::isRAW(const TQString& file)
{
#if KDCRAW_VERSION < 0x000106
    TQString rawFilesExt(KDcrawIface::DcrawBinary::instance()->rawFiles());
#else
    TQString rawFilesExt(KDcrawIface::KDcraw::rawFiles());
#endif

    TQFileInfo fileInfo(file);
    if (rawFilesExt.upper().contains( fileInfo.extension(false).upper() ))
        return true;

    return false;
}

bool Utils::CopyFile(const TQString& src, const TQString& dst)
{
    TQFile sFile(src);
    TQFile dFile(dst);

    if ( !sFile.open(IO_ReadOnly) )
        return false;

    if ( !dFile.open(IO_WriteOnly) )
    {
        sFile.close();
        return false;
    }

    const int MAX_IPC_SIZE = (1024*32);
    char buffer[MAX_IPC_SIZE];

    TQ_LONG len;
    while ((len = sFile.readBlock(buffer, MAX_IPC_SIZE)) != 0)
    {
        if (len == -1 || dFile.writeBlock(buffer, (TQ_ULONG)len) == -1)
        {
            sFile.close();
            dFile.close();
            return false;
        }
    }

    sFile.close();
    dFile.close();

    return true;
}

bool Utils::MoveFile(const TQString& src, const TQString& dst)
{
    struct stat stbuf;
    if (::stat(TQFile::encodeName(dst), &stbuf) != 0)
    {
        tqDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to stat src");
        return false;
    }
    
    if (!CopyFile(src, dst))
        return false;

    struct utimbuf timbuf;
    timbuf.actime = stbuf.st_atime;
    timbuf.modtime = stbuf.st_mtime;
    if (::utime(TQFile::encodeName(dst), &timbuf) != 0)
    {
        tqDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to update dst time");
    }
    
    if (::unlink(TQFile::encodeName(src).data()) != 0)
    {
        tqDebug("KIPIJPEGLossLessPlugin:MoveFile: failed to unlink src");
    }
    return true;
}

bool Utils::deleteDir(const TQString& dirPath)
{
    TQDir dir(dirPath);
    if (!dir.exists()) 
        return false;

    dir.setFilter(TQDir::Dirs | TQDir::Files | TQDir::NoSymLinks);

    const TQFileInfoList* infoList = dir.entryInfoList();
    if (!infoList) 
        return false;

    TQFileInfoListIterator it(*infoList);
    TQFileInfo* fi;

    while( (fi = it.current()) ) 
    {
        ++it;
        if(fi->fileName() == "." || fi->fileName() == ".." )
            continue;

        if( fi->isDir() ) 
        {
            deleteDir(fi->absFilePath());
        }
        else if( fi->isFile() )
            dir.remove(fi->absFilePath());
    }

    dir.rmdir(dir.absPath());
    return true;
}

}  // NameSpace KIPIJPEGLossLessPlugin
