/* temporaryfilecache.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2011-2022 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
 */

#include "temporaryfilecache.hh"
#include "worker.h"
#include "datei.h"
#include "worker_locale.h"
#include "aguix/lowlevelfunc.h"
#include "aguix/request.h"
#include "nwc_path.hh"
#include <iostream>

TemporaryFileCache *TemporaryFileCache::m_instance = NULL;

TemporaryFileCache::TemporaryFileCache()
{
}

TemporaryFileCache::~TemporaryFileCache()
{
    if ( ! m_entries.empty() ) {
        std::cerr << "Worker: There are still temporary files existing, that should not happen!" << std::endl;

        cleanupCache();
    }
}

TemporaryFileCache::TemporaryFileCacheEntry TemporaryFileCache::getCopy( const std::string &filename,
                                                                         CopyfileProgressCallback *progress_callback )
{
    if ( m_entries.count( filename ) == 0 ) {
        if ( createTempFile( filename, progress_callback ) != 0 ) {
            return TemporaryFileCacheEntry( *this );
        }
        m_entries[filename].ref_count = 1;
    } else {
        m_entries[filename].ref_count++;
    }

    return TemporaryFileCacheEntry( *this, filename, m_entries[filename].temp_name );
}

const std::string &TemporaryFileCache::TemporaryFileCacheEntry::getTempName() const
{
    return m_tempname;
}

TemporaryFileCache::TemporaryFileCacheEntry::TemporaryFileCacheEntry( TemporaryFileCache &cache ) : m_cache( cache ),
                                                                                                    m_valid( false )
{
}

TemporaryFileCache::TemporaryFileCacheEntry::TemporaryFileCacheEntry( TemporaryFileCache &cache,
                                                                      const std::string &filename,
                                                                      const std::string &tempname ) : m_cache( cache ),
                                                                                                      m_filename( filename ),
                                                                                                      m_tempname( tempname ),
                                                                                                      m_valid( true )
{
}

TemporaryFileCache::TemporaryFileCacheEntry::~TemporaryFileCacheEntry()
{
    if ( m_valid ) {
        m_cache.unrefCopy( m_filename );
    }
}

TemporaryFileCache::TemporaryFileCacheEntry::TemporaryFileCacheEntry( const TemporaryFileCacheEntry &other ) : m_cache( other.m_cache ),
                                                                                                               m_filename( other.m_filename ),
                                                                                                               m_tempname( other.m_tempname ),
                                                                                                               m_valid( other.m_valid )
{
    m_cache.refCopy( m_filename );
}

TemporaryFileCache::TemporaryFileCacheEntry &TemporaryFileCache::TemporaryFileCacheEntry::operator=( const TemporaryFileCacheEntry &rhs )
{
    if ( this != &rhs ) {
        m_cache.refCopy( rhs.m_filename );
        m_cache.unrefCopy( m_filename );
        m_filename = rhs.m_filename;
        m_tempname = rhs.m_tempname;
        m_valid = rhs.m_valid;
    }

    return *this;
}

bool TemporaryFileCache::TemporaryFileCacheEntry::isValid() const
{
    return m_valid;
}

void TemporaryFileCache::unrefCopy( const std::string &filename )
{
    if ( m_entries.count( filename ) == 0 ) {
    } else if ( m_entries[filename].ref_count == 1 ) {
        removeTempFile( filename );
        m_entries.erase( filename );
    } else {
        m_entries[filename].ref_count--;
    }
}

void TemporaryFileCache::refCopy( const std::string &filename )
{
    if ( m_entries.count( filename ) == 0 ) {
    } else {
        m_entries[filename].ref_count++;
    }
}

void TemporaryFileCache::cleanupCache()
{
    for ( std::map< std::string, temp_file_info_t >::iterator it1 = m_entries.begin();
          it1 != m_entries.end();
          it1++ ) {
        removeTempFile( it1->first );
    }
}

int TemporaryFileCache::removeTempFile( const std::string &filename )
{
    worker_struct_stat stbuf;
    bool changed = false;

    if ( ! m_entries[filename].temp_name.empty() ) {
	if ( worker_lstat( m_entries[filename].temp_name.c_str(), &stbuf ) != 0 ) changed = true;
	else if ( m_entries[filename].mod_time != stbuf.st_mtime ) changed = true;
	
	if ( changed == true &&
	     Worker::getRequester() != NULL ) {
            char *reqstr;
            reqstr = (char*)_allocsafe( strlen( catalog.getLocale( 628 ) ) + filename.length() + 1 );
            sprintf( reqstr, catalog.getLocale( 628 ), filename.c_str() );
            Worker::getRequester()->request( catalog.getLocale( 125 ), reqstr, catalog.getLocale( 11 ) );
            _freesafe( reqstr );
	}
	
        worker_unlink( m_entries[filename].temp_name.c_str() );
    }
    return 0;
}

int TemporaryFileCache::createTempFile( const std::string &filename,
                                        CopyfileProgressCallback *progress_callback )
{
    worker_struct_stat stbuf;
    char *newtempname;

    if ( worker_lstat( filename.c_str(), &stbuf ) != 0 ) return 1;

    if ( ! S_ISREG( stbuf.st_mode ) &&
         ! S_ISLNK( stbuf.st_mode ) ) {
        return 1;
    }

    auto basename = NWC::Path::basename( filename );
    std::string::size_type pos = basename.rfind( "." );

    if ( pos != std::string::npos ) {
        std::string suffix( basename, pos );
        newtempname = Datei::createTMPName( NULL, suffix.c_str() );
    } else {
        newtempname = Datei::createTMPName();
    }

    if ( newtempname == NULL ) return 1;

    if ( Datei::copyfile( newtempname, filename.c_str(),
                          progress_callback, true ) != 0 ) {
        if ( Worker::getRequester() != NULL ) {
            char *reqstr;
            reqstr = (char*)_allocsafe( strlen( catalog.getLocale( 618 ) ) + filename.length() + 1 );
            sprintf( reqstr, catalog.getLocale( 618 ), filename.c_str() );
            Worker::getRequester()->request( catalog.getLocale( 347 ), reqstr, catalog.getLocale( 11 ) );
            _freesafe( reqstr );
        }

        worker_unlink( newtempname );
        _freesafe( newtempname );
        return 1;
    }

    m_entries[filename].temp_name = newtempname;
    m_entries[filename].ref_count = 1;
    if ( worker_lstat( newtempname, &stbuf ) != 0 ) m_entries[filename].mod_time = 0;
    else m_entries[filename].mod_time = stbuf.st_mtime;
  
    _freesafe( newtempname );

    return 0;
}

TemporaryFileCache &TemporaryFileCache::getInstance()
{
    if ( m_instance == NULL ) {
        m_instance = new TemporaryFileCache();
    }

    return *m_instance;
}

void TemporaryFileCache::destroyInstance()
{
    if ( m_instance != NULL ) {
        delete m_instance;
        m_instance = NULL;
    }
}
