/***************************************************************************
**
**  This file is part of QGpCoreTools.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This file 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 Lesser General Public
**  License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2006-07-06
**  Copyright: 2006-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#ifndef CACHE_H
#define CACHE_H

#include "QGpCoreToolsDLLExport.h"
#include "Translations.h"
#include "Mutex.h"

namespace QGpCoreTools {

#define INV_MEGABYTES 9.5367431640625e-07
#define MEGABYTES 1048576.0

class CacheItem;

class QGPCORETOOLS_EXPORT Cache
{
  TRANSLATIONS("Cache")
public:
  Cache();
  ~Cache() {}

  // Parameters, not changed while cache is running
  void setSize(double nMegaBytes) {_maxLoadedBytes=nMegaBytes * MEGABYTES;}
  void setSwapDir(const QDir& d);

  // Memory allocation and desallocation
  bool makeAvailable(const CacheItem * item);
  void free(CacheItem * item, bool saveTemp=true);
  bool enlarge(CacheItem * item, double finalSize);
  void free();

  double freeBytes() const {return _maxLoadedBytes -_loadedBytes;}
  double freeMegaBytes() const {return freeBytes() * INV_MEGABYTES;}

  void debugStatus(const QString& tag) const;
private:
  friend class CacheItem;
  bool free(double byteSize);
  const CacheItem * bestToFree();
  QString humanInfo() const;

  QList<const CacheItem *> _allocatedList;
  double _maxLoadedBytes;
  double _loadedBytes;
  QDir _swapDir;
  mutable Mutex _mutex;
};

} // namespace QGpCoreTools

#endif // CACHE_H
