package org.kne.cloud.network.minecraft;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

import org.kne.cloud.network.StreamBridge;

public class MinecraftStreamBridge extends StreamBridge {
	private List<Function<MinecraftPacket,MinecraftPacket>>transformers=new ArrayList<Function<MinecraftPacket,MinecraftPacket>>();
	public List<Function<MinecraftPacket, MinecraftPacket>> getTransformers() {
		return transformers;
	}

	@Override
	public void runTask() {
		MinecraftInputStream min=(MinecraftInputStream) in;
		MinecraftOutputStream mout=(MinecraftOutputStream) out;
		try {
			MinecraftPacket mp=null;
				while ((mp=min.readPacket())!=null) {
					for (Iterator<Function<MinecraftPacket, MinecraftPacket>> iterator = transformers.iterator(); iterator.hasNext();) {
						Function<MinecraftPacket, MinecraftPacket> function = (Function<MinecraftPacket, MinecraftPacket>) iterator
								.next();
						mp=function.apply(mp);
					}
					mout.writePacket(mp);
					mout.flush();
					Thread.yield();
					//System.out.println(mp);
				}
				//super.runTask();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}finally {
				try {
					in.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
				try {
					out.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
	}

	public MinecraftStreamBridge(InputStream in,MinecraftProtocolContext cin, OutputStream out,MinecraftProtocolContext cout, boolean server) {
		super(new MinecraftInputStream( in,cin), new MinecraftOutputStream( out,cout));
	}
	
}
