import operator
import os
import string
import tempfile
import time
import types

from compClust.iplot.Plot import Plot

class PlotCache:
  """manage collection of plots
  """
  def __init__(self):
    self.__cache = {}
    self.__ctime = {}
    self.__atime = {}

  def __get_plot_id(self, plot):
    return str(plot.id)
  
  def append(self, plot):
    """Update cache with created plot
    """
    self.__cache[self.__get_plot_id(plot)] = plot
    timestamp = time.time()
    self.__ctime[self.__get_plot_id(plot)] = timestamp
    self.__atime[self.__get_plot_id(plot)] = timestamp
    return self.__get_plot_id(plot)

  def has_key(self, key):
    if isinstance(key, Plot):
      key = self.__get_plot_id(key)
    return self.__cache.has_key(key)

  def get(self, key, default):
    """Retrive a plot with a default value
    """
    if isinstance(key, Plot):
      key = self.__get_plot_id(key)

    try:
      return self.__cache[key]
    except KeyError:
      return default
    
  def __getitem__(self, key):
    """Retrieve a plot, keeping track of the last access time
    """
    if isinstance(key, Plot):
      key = self.__get_plot_id(key)

    plot = self.__cache[key]
    self.__atime[key] = time.time()
    return plot

  def items(self):
    for k in self.__cache.keys():
      self.__atime[k] = time.time
    return self.__cache.items()

  def keys(self):
    return self.__cache.keys()

  def __len__(self):
    return len(self.__cache)

  def setdefault(self, key, value):
    """Set key to value if its not already set"""
    return self.__cache.setdefault(key, value)

  def sizeof(self):
    """Estimate memory used
    """
    if len(self.__cache) == 0:
      return 0
    else:
      return reduce(operator.add,
                    [x.sizeof() for x in self.__cache.values()])
    
  def values(self):
    for k in self.__cache.keys():
      self.__atime[k] = time.time
    return self.__cache.values()

  def atime(self, plot):
    """return when the plot was last accessed"""
    return self.__atime[plot]
  
  def ctime(self, plot):
    """return when the plot was created"""
    return self.__ctime[plot]

