package net.lax1dude.eaglercraft.beta;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

import net.lax1dude.eaglercraft.Filesystem;
import net.lax1dude.eaglercraft.internal.vfs2.VFile2;
import net.minecraft.src.IChunkLoader;
import net.minecraft.src.ISaveHandler;
import net.minecraft.src.NBTBase;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.WorldInfo;
import net.minecraft.src.WorldProvider;
import net.minecraft.src.WorldProviderHell;

public class EaglercraftSaveHandler implements ISaveHandler {
	
	public final String directory;
	public VFile2 savedir;
	
	public EaglercraftSaveHandler(String dir) {
		this.directory = dir;
	}

	@Override
	public WorldInfo loadWorldInfo() {
		this.savedir = new VFile2(directory + "/lvl");
		byte[] file = savedir.getAllBytes();
		if(file != null) {
			try {
				NBTBase nbt = NBTBase.readTag(new DataInputStream(new ByteArrayInputStream(file)));
				if(nbt instanceof NBTTagCompound) {
					return new WorldInfo((NBTTagCompound)nbt);
				}
			} catch (IOException e) {
				System.err.println("Failed to load world data for '" + directory + "/lvl'");
				e.printStackTrace();
			}
		}
		return null;
	}

	public void checkSessionLock() {
	}

	@Override
	public IChunkLoader getChunkLoader(WorldProvider worldprovider) {
		if(worldprovider instanceof WorldProviderHell) {
			return new EaglercraftChunkLoader(directory + "/c1");
		}else {
			return new EaglercraftChunkLoader(directory + "/c0");
		}
	}

	@Override
	public void saveWorldInfoAndPlayer(WorldInfo worldinfo, List list) {
		ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
		DataOutputStream ds = new DataOutputStream(out);
		try {
			NBTBase.writeTag(worldinfo.getNBTTagCompoundWithPlayer(list), ds);
		} catch (IOException e) {
			System.err.println("Failed to serialize world data for '" + directory + "/lvl'");
			e.printStackTrace();
			return;
		}
		this.savedir = new VFile2(directory + "/lvl");
		savedir.setAllBytes(out.toByteArray());
	}

	@Override
	public void saveWorldInfo(WorldInfo worldinfo) {
		ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
		DataOutputStream ds = new DataOutputStream(out);
		try {
			NBTBase.writeTag(worldinfo.getNBTTagCompound(), ds);
		} catch (IOException e) {
			System.err.println("Failed to serialize world data for '" + directory + "/lvl'");
			e.printStackTrace();
			return;
		}
		this.savedir = new VFile2(directory + "/lvl");
		savedir.setAllBytes(out.toByteArray());
	}

}
