package net.minecraft.src;

import net.lax1dude.eaglercraft.internal.vfs2.VFile2;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class RegionFileCache {
	private static final Map regionFiles = new HashMap();

	public static synchronized RegionFile getRegionFile(VFile2 var0, int var1, int var2) {
		VFile2 var3 = new VFile2(var0, "region");
		VFile2 var4 = new VFile2(var3, "r." + (var1 >> 5) + "." + (var2 >> 5) + ".mcr");
		RegionFile var5 = (RegionFile) regionFiles.get(var4);
		if(var5 != null) {
			if(var5 != null) {
				return var5;
			}
		}

		if(regionFiles.size() >= 256) {
			func_22192_a();
		}

		var5 = new RegionFile(var4);
		regionFiles.put(var4, var5);
		return var5;
	}

	public static synchronized void func_22192_a() {
		Iterator var0 = regionFiles.values().iterator();

		while(var0.hasNext()) {
			RegionFile var1 = (RegionFile) var0.next();

			try {
                if(var1 != null) {
					var1.func_22196_b();
				}
			} catch (IOException var3) {
				var3.printStackTrace();
			}
		}

		regionFiles.clear();
	}

	public static int func_22191_b(VFile2 var0, int var1, int var2) {
		RegionFile var3 = getRegionFile(var0, var1, var2);
		return var3.func_22209_a();
	}

	public static DataInputStream getChunkInputStream(VFile2 var0, int var1, int var2) {
		RegionFile var3 = getRegionFile(var0, var1, var2);
		return var3.func_22210_a(var1 & 31, var2 & 31);
	}

	public static DataOutputStream getChunkOutputStream(VFile2 var0, int var1, int var2) {
		RegionFile var3 = getRegionFile(var0, var1, var2);
		return var3.func_22205_b(var1 & 31, var2 & 31);
	}
}
