/* temporaryfilecache.hh
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2011 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * 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.
 *
 * 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifndef TEMPORARYFILECACHE_HH
#define TEMPORARYFILECACHE_HH

#include "wdefines.h"
#include <string>
#include <map>
#include <utility>

class CopyfileProgressCallback;

class TemporaryFileCache
{
public:
    TemporaryFileCache();
    ~TemporaryFileCache();

    class TemporaryFileCacheEntry
    {
    public:
        TemporaryFileCacheEntry( TemporaryFileCache &cache );
        TemporaryFileCacheEntry( const TemporaryFileCacheEntry &other );
        ~TemporaryFileCacheEntry();
        
        TemporaryFileCacheEntry &operator=( const TemporaryFileCacheEntry &rhs );

        const std::string &getTempName() const;

        bool isValid() const;
    protected:
        friend class TemporaryFileCache;
        TemporaryFileCacheEntry( TemporaryFileCache &cache,
                                 const std::string &filename,
                                 const std::string &tempname );
    private:
        TemporaryFileCache &m_cache;
        std::string m_filename;
        std::string m_tempname;
        bool m_valid;
    };

    TemporaryFileCacheEntry getCopy( const std::string &filename,
                                     CopyfileProgressCallback *progress_callback = NULL );

    static TemporaryFileCache &getInstance();
    static void destroyInstance();
protected:
    void unrefCopy( const std::string &filename );
    void refCopy( const std::string &filename );
private:
    void cleanupCache();
    int removeTempFile( const std::string &filename );
    int createTempFile( const std::string &filename,
                        CopyfileProgressCallback *progress_callback = NULL );

    typedef struct {
        std::string temp_name;
        int ref_count;
        time_t mod_time;
    } temp_file_info_t;

    std::map< std::string, temp_file_info_t > m_entries;

    static TemporaryFileCache *m_instance;
};

#endif
