package cn.citycraft.GsonAgent.normal.bind;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import com.google.gson.TypeAdapter;

import cn.citycraft.GsonAgent.normal.JsonElementHandle;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class TypeAdapterHandle<T> implements cn.citycraft.GsonAgent.api.TypeAdapter<T> {

	private final TypeAdapter<T> handle;

	public TypeAdapterHandle(final TypeAdapter handle) {
		this.handle = handle;
	}

	@Override
	public T fromJson(final Reader in) throws IOException {
		return getHandle().fromJson(in);
	}

	@Override
	public T fromJson(final String json) throws IOException {
		return getHandle().fromJson(json);
	}

	@Override
	public T fromJsonTree(final cn.citycraft.GsonAgent.api.JsonElement jsonTree) {
		return getHandle().fromJsonTree(((JsonElementHandle) jsonTree).getHandle());
	}

	@Override
	public TypeAdapter<T> getHandle() {
		return handle;
	}

	@Override
	public TypeAdapterHandle<T> nullSafe() {
		return new TypeAdapterHandle(this.handle);
	}

	@Override
	public T read(final cn.citycraft.GsonAgent.api.stream.JsonReader reader) throws IOException {
		if (reader.peek().name().equals("NULL")) {
			reader.nextNull();
			return null;
		}
		return this.read(reader);
	}

	@Override
	public String toJson(final T value) throws IOException {
		return getHandle().toJson(value);
	}

	@Override
	public void toJson(final Writer out, final T value) throws IOException {
		getHandle().toJson(out, value);
	}

	@Override
	public JsonElementHandle toJsonTree(final T value) {
		return new JsonElementHandle(getHandle().toJsonTree(value));
	}

	@Override
	public void write(final cn.citycraft.GsonAgent.api.stream.JsonWriter out, final T value) throws IOException {
		if (value == null) {
			out.nullValue();
		} else {
			this.write(out, value);
		}
	}

}
