package CC200_httpserver_Package_Request;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;


/*
 * ·â×°Request:GETºÍPOSTÍ·ÐÅÏ¢ÖÐÄÃ¶«Î÷
 *
 */
public class Request {
	//1.ÇëÇó·½Ê½
	private String method;
	//2.ÇëÇó×ÊÔ´
	private String url;
	//3.ÇëÇó²ÎÊý:Ò»¸ökey--¶à¸övalueµÄÐÎÊ½
	private Map<String, List<String>> paramMapValues;

	//ÄÚ²¿
	public static final String CRLF="\r\n";
	protected InputStream is;
	private String requestInfo;
	
	public Request() {
		method="";
		url="";
		paramMapValues=new HashMap<String, List<String>>();
		requestInfo="";
	}
	public Request(InputStream is)  {
		this();
		this.is=is;
		try {
			byte []data=new byte[20480];
			int len;
			len = is.read(data);
			requestInfo=new String(data,0,len);
		} catch (IOException e) {
			return;
		}
		//·ÖÎöÍ·ÐÅÏ¢
		parseRequestInfo();
	}
	/**
		·ÖÎöÍ·ÐÅÏ¢
	 */
	private void parseRequestInfo() {
		if (requestInfo==null||(requestInfo=requestInfo.trim()).equals("")) {
			return;
		}
		/*
		 * ========================
		 * ´ÓÐÅÏ¢µÄÊ×ÐÐ·Ö½â³ö£ºÇëÇó·½Ê½method£¬ÇëÇóÂ·¾¶url£¬ÇëÇó²ÎÊýparaString(get¿ÉÄÜ´æÔÚÇëÇó²ÎÊý)£¬
		 * 	GET /?username=%601111111111&pwd=11111111 HTTP/1.1
		 * 	POST·½Ê½£¬²ÎÊý¿ÉÄÜÔÚ×îºó
		 * =========================
		 */
		String paramString="";//½ÓÊÕÇëÇó²ÎÊý
		
		//1.»ñÈ¡ÇëÇó·½Ê½(µ½»»ÐÐ½áÊø)ºÍÇëÇóÂ·¾¶urlÒÔ¼°ÇëÇó²ÎÊý
		String firstLine=requestInfo.substring(0, requestInfo.indexOf(CRLF));
		int idx=requestInfo.indexOf("/");
		this.method=firstLine.substring(0, idx).trim();
		String urlstr=firstLine.substring(idx, firstLine.indexOf("HTTP/")).trim();
		if (this.method.equalsIgnoreCase("POST")) {
			this.url=urlstr;
			//²ÎÊý£ºPOSTµÄ²ÎÊýÔÚ×îºóÒ»¸ö»»ÐÐÏÂÃæ
			paramString=requestInfo.substring(requestInfo.lastIndexOf(CRLF));
		}else if(this.method.equalsIgnoreCase("GET")){
			if (urlstr.contains("?")) {//ÊÇ·ñ´æÔÚ²ÎÊý
				String[] urlArray=urlstr.split("\\?");//·Ö¸î³ö£¿Ç°ÃæµÄ¼´ÊÇurl
				this.url=urlArray[0];
				paramString=urlArray[1];//·Ö¸î³ö²ÎÊý
			}else{
				this.url=urlstr;
			}
		}
		

		
		if (paramString.equals("")) {//²»´æÔÚÇëÇó²ÎÊý
			return;
		}
		//2.½«ÇëÇó²ÎÊý·â×°µ½MAPÖÐ
		parseParam(paramString);
		
	}
	/**
	 * ½«ÇëÇó²ÎÊý·â×°µ½MAPÖÐ
	 */

	public void  parseParam(String paramString) {
		//1.·Ö¸î ½«×Ö·û´®×ª³ÉÊý×é//Ò²¿ÉÒÔÓÃsplit
		StringTokenizer token=new StringTokenizer(paramString,"&");
		while (token.hasMoreTokens()) {
			String keyValue=token.nextToken();
			String []keyValues=keyValue.split("=");
			if (keyValues.length==1) {//Öµ²»´æÔÚ£¬±ÈÈçname=&...,ÔòÉèÖÃname=null&
				keyValues=Arrays.copyOf(keyValues,2);
				keyValues[1]=null;
			}
			//×ª³ÉMAP
			//ÏÈÄÃkey
			String key=keyValues[0].trim();
				//ÕâÀï½âÂë
			//ÔÙÄÃvalue
			String value=(null==keyValues[1])?null:decoder(keyValues[1].trim(),"GBK");
			if (!paramMapValues.containsKey(key)) {
				paramMapValues.put(key, new ArrayList<String>());

			}
			List<String> values =paramMapValues.get(key);
			values.add(value);
		}
	}
	/*
	 * ½âÂë:½â¾öµÇÂ¼ÓÃ»§ÃûÖÐÎÄÂÒÂë
	 */
	private String decoder(String value,String code) {
		try {
			return java.net.URLDecoder.decode(value,code);
		} catch (UnsupportedEncodingException e) {
			return null;
//			e.printStackTrace();
		}
	}
	/*
	 * ¸ù¾ÝÒ³ÃæµÄname »ñÈ¡¶ÔÓ¦µÄ¶à¸öÖµ
	 */
	public String[] getParametValues(String name) {
		List<String> values=null;
		if((values=paramMapValues.get(name))==null){
			return null;
		}else {
			return values.toArray(new String[0]);
		}
	}
	/*
	 * ¸ù¾ÝÒ³ÃæµÄname »ñÈ¡¶ÔÓ¦µÄµ¥¸öÖµ(µÚÒ»¸ö)values[0]
	 */
	public String getParamet(String name) {
		 String[] values=getParametValues(name);
		 if (values==null) {
			return null;
		}
		 return values[0];
	}
	
	//·½±ãÍâ²¿»ñÈ¡URL
	public String getUrl() {
		return url;
	}	
	
}
