package org.kne.cloud.network;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

import javax.naming.OperationNotSupportedException;

public class ProtocolDetector extends ArrayList<ProtocolDetectorItem>{

	public static ProtocolDetector getNewDefaultDetector() {
		ProtocolDetector pd=new ProtocolDetector();
		pd.add(new KLALBDetectorItem());
		pd.add(new RDPDetectorItem());
			pd.add(new HTTPDetectorItem());
			pd.add(new HTTPSDetectorItem());
			pd.add(new SSHDetectorItem());
		return pd;
	}
	public ProtocolStack detect(InputStream ins) throws IOException {
		if(!ins.markSupported())
			throw new IOException("mark not supported");
		ProtocolStack psk=new ProtocolStack();
		Stack<ProtocolDetectorItem> detectorS=new Stack<ProtocolDetectorItem>();
		ins.mark(8192);
		detectProtocol(psk,detectorS,ins);
		return psk;
	}

	private void detectProtocol(ProtocolStack psk,Stack<ProtocolDetectorItem>  detectorS2, InputStream ins) throws IOException {
		for (Iterator<ProtocolDetectorItem> iterator = iterator(); iterator.hasNext();) {
			ProtocolDetectorItem protocolDetector = (ProtocolDetectorItem) iterator.next();
			detectorS2.forEach((e)->{
				e.apply(ins);
			});
			Protocol p=protocolDetector.apply(ins);
			ins.reset();
			if(p!=null) {
				detectorS2.push(protocolDetector);
				psk.push(p);
				detectProtocol(psk,detectorS2,ins);
				return;
			}
			
		}
	}
}
