/*
 * vdr-podcatcher - A plugin for the Linux Video Disk Recorder
 * Copyright (c) 2006 Tobias Grimm <vdr@e-tobi.net>
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * $Id: localfilecache.cc 3219 2006-04-16 15:06:35Z svntobi $
 *
 */

#include <sys/stat.h>
#include <fstream>
#include <dirent.h>
#include "localfilecache.h"
#include "sdbmhashcalculator.h"

using namespace std;

LocalFileCache::LocalFileCache(string cacheDirName)
:cacheDirName(cacheDirName)
{
}

ref_ptr<istream> LocalFileCache::CreateStreamByUrl(string url)
{
    ifstream* localFile = new ifstream();
    localFile->open(UrlToLocalFileName(url).c_str());
    if (! localFile->fail())
    {
        return ref_ptr<istream>(localFile);
    }
    else
    {
        delete localFile;
        return ref_ptr<istream>(NULL);
    }
}

void LocalFileCache::Put(istream& document, string url)
{
    ofstream localFile(UrlToLocalFileName(url).c_str());
    localFile << document.rdbuf();
}

string LocalFileCache::UrlToLocalFileName(string url)
{
    return cacheDirName + "/" +  SdbmHashCalculator::Calculate(url);
}

int LocalFileCache::GetAge(string url)
{
    struct stat buf;
    time_t tm = time(NULL);

    if (0 == stat(UrlToLocalFileName(url).c_str(), &buf))
    {
        return (tm - buf.st_mtime) / 60 / 60;
    }

    return 0;
}

bool LocalFileCache::IsCached(string url)
{
    struct stat buf;
    if (0 == stat(UrlToLocalFileName(url).c_str(), &buf))
    {
        return true;
    }
    else
    {
        return false;
    }
}

void LocalFileCache::CleanUp(int maxAge)
{
    DIR* directory = opendir(cacheDirName.c_str());

    if (directory)
    {
        struct dirent* entry;
        while ((entry = readdir(directory)))
        {
            string fileName =  entry->d_name;
            if ((fileName != ".") & (fileName != ".."))
            {
                fileName = string(cacheDirName) + "/" + fileName;
                if (GetLocalFileAge(fileName) >= maxAge)
                {
                    remove(fileName.c_str());
                }
            }
        }
    }

    closedir(directory);
}

int LocalFileCache::GetLocalFileAge(string localFileName)
{
    struct stat buf;
    time_t tm = time(NULL);

    if (0 == stat(localFileName.c_str(), &buf))
    {
        return (tm - buf.st_mtime) / 60 / 60;
    }

    return 0;
}
