package cn.net.caoyao.cpzshandset.common.bitmap;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import android.graphics.Bitmap;

public class MemoryCache
{
  private Map<String, Bitmap> cache = Collections.synchronizedMap(new LinkedHashMap(10, 1.5F, true));

  private long size = 0L;

  private long limit = 2097152L;

  public MemoryCache()
  {
    if (Runtime.getRuntime().maxMemory() / 10L > this.limit)
    {
      setLimit(2097152L);
    }
    else
    {
      setLimit(Runtime.getRuntime().maxMemory() * 2L / 25L);
    }
  }

  public void setLimit(long new_limit) {
    this.limit = new_limit;
  }

  public Bitmap get(String id) {
    try {
      if (!this.cache.containsKey(id))
        return null;
      return (Bitmap)this.cache.get(id); } catch (NullPointerException ex) {
    }
    return null;
  }

  public void put(String id, Bitmap bitmap)
  {
    try {
      if (!this.cache.containsKey(id))
      {
        checkSize();

        this.cache.put(id, bitmap);
        this.size += getSizeInBytes(bitmap);
      }
    } catch (Throwable th) {
      th.printStackTrace();
    }
  }

  private void checkSize()
  {
    if (this.size > this.limit * 0.65D)
    {
      Iterator iter = this.cache.entrySet().iterator();
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry)iter.next();
        this.size -= getSizeInBytes((Bitmap)entry.getValue());
        iter.remove();
        if (this.size <= this.limit * 0.65D)
          break;
      }
    }
  }

  public void clear() {
    this.cache.clear();
  }

  long getSizeInBytes(Bitmap bitmap)
  {
    if (bitmap == null)
      return 0L;
    return bitmap.getRowBytes() * bitmap.getHeight();
  }
}