package com.morgan.library.snippet;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.morgan.library.app.APPContext;
import com.morgan.library.utils.Logger;

/**
 * 因为一些需要，在Webview中需要用到登陆时候的cookie，所以要做到cookie共享。
 * 
 * @author Morgan.Ji
 * 
 */
public class CookieShare {

    /**
     * 使用用户名和密码登陆，获取得到的cookie并同步
     * 
     * @param name
     * @param pass
     * @return
     */
    public boolean login(String name, String pass) {
        boolean result = false;
        try {
            String loginUrl = "http://10.1.1.157:8080/cas/login";
            BasicCookieStore bcsc = new BasicCookieStore();
            DefaultHttpClient client = new DefaultHttpClient();
            client.setCookieStore(bcsc);
            // get访问登陆页面
            HttpGet get = new HttpGet(loginUrl);
            HttpResponse response = client.execute(get);
            // 拿body
            String bodyAsString = EntityUtils.toString(response.getEntity());
            // 拿jsessionid
            String action = bodyAsString.substring(bodyAsString.indexOf("action") + 8,
                    bodyAsString.indexOf("action") + 64);
            String jessionid = action.split("=")[1];
            Logger.i("jessionid", jessionid);
            // 拿lt
            String lt = bodyAsString.substring(bodyAsString.indexOf("name=\"lt\"") + 17,
                    bodyAsString.indexOf("name=\"lt\"") + 56);
            Logger.i("lt", lt);
            // 拿excution
            String execution = "e1s1";
            // post提交表单
            HttpPost post = new HttpPost(loginUrl);
            // 设置一系列的值
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("username", name));
            nvps.add(new BasicNameValuePair("password", pass));
            nvps.add(new BasicNameValuePair("lt", lt));
            nvps.add(new BasicNameValuePair("execution", execution));
            nvps.add(new BasicNameValuePair("_eventId", "submit"));
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

            response = client.execute(post);
            bodyAsString = EntityUtils.toString(response.getEntity());
            Logger.i("cookie", bcsc.getCookies().toString());
            // Logger.i("login response", bodyAsString);
            // 如果登陆成功，同步cookie
            if (bodyAsString.indexOf("id=\"msg\" class=\"success\"") > 0) {
                result = true;
                synCookies("http://10.1.1.175", bcsc.getCookies());
                // 访问其他的api
                get = new HttpGet("http://10.1.1.175:8088/ioc/restapi/emergencyEvent/getEventByReportName");
                response = client.execute(get);
                bodyAsString = EntityUtils.toString(response.getEntity());
                Logger.i("get list response", bodyAsString);
            }
        } catch (Exception e) {
            Logger.i("error", e.getMessage());
        }
        return result;
    }

    /**
     * 同步一下cookie
     * 
     * @param url
     *            cookie所属的url
     * @param cookieList
     *            cookie列表
     */
    public void synCookies(String url, List<Cookie> cookieList) {
        String cookies = "";
        if (cookieList.isEmpty()) {
            return;
        }
        for (int i = 0; i < cookieList.size(); i++) {
            cookies = cookieList.get(i).getName() + "=" + cookieList.get(i).getValue() + ";domain="
                    + cookieList.get(i).getDomain();
        }
        CookieSyncManager.createInstance(APPContext.getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        // 移除老的cookie（但是这个调用会报错,故暂时注释掉）
        // cookieManager.removeSessionCookie();
        cookieManager.setCookie(url, cookies);
        CookieSyncManager.getInstance().sync();
    }
}

@@ -1500,279 +1500,8 @@
 ));%0A
-            // %E6%8B%BFjsessionid%0A            String action = bodyAsString.substring(bodyAsString.indexOf(%22action%22) + 8,%0A                    bodyAsString.indexOf(%22action%22) + 64);%0A            String jessionid = action.split(%22=%22)%5B1%5D;%0A            Logger.i(%22jessionid%22, jessionid);%0A
     
@@ -3302,17 +3302,58 @@
 ie%E6%89%80%E5%B1%9E%E7%9A%84url
+,%E8%BF%99%E4%B8%AAurl%E5%BF%85%E9%A1%BB%E8%A6%81%E5%92%8Cdomain%E7%9B%B8%E5%90%8C(cookie%E5%86%85%E7%9A%84domain%E5%AD%97%E6%AE%B5%E5%8F%AF%E4%BB%A5%E5%8E%BB%E6%8E%89);
 %0A
-
      * @
@@ -3491,17 +3491,16 @@
 g cookie
-s
  = %22%22;%0A 
@@ -3568,225 +3568,8 @@
   %7D%0A
-        for (int i = 0; i %3C cookieList.size(); i++) %7B%0A            cookies = cookieList.get(i).getName() + %22=%22 + cookieList.get(i).getValue() + %22;domain=%22%0A                    + cookieList.get(i).getDomain();%0A        %7D%0A
     
@@ -3827,24 +3827,234 @@
 onCookie();%0A
+        for (int i = 0; i %3C cookieList.size(); i++) %7B%0A            cookie = cookieList.get(i).getName() + %22=%22 + cookieList.get(i).getValue() + %22;domain=%22%0A                    + cookieList.get(i).getDomain();%0A    
         cook
@@ -4088,12 +4088,21 @@
 okie
-s
 );%0A
+        %7D%0A
     

fix cookie share bug