package com.example.mountaintravel.util;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.util.Log;

import com.example.mountaintravel.variable.Variable;
import com.smart.gtstrvl.MainActivity;

public class LoginUtil {
	public static String code="";
	public static  String loginByHttpClientGet() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/islogin";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if ( !Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				String result = StreamTools.streamToString(is);
				JSONObject json = new JSONObject(result);
				 code= json.getString("code");
				
				return code;
				

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "err";
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
		return code;
	}
	
}
