package com.sipai.jspatrol.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.PersistentCookieStore;

import org.apache.http.cookie.Cookie;

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

/**
 * Created by lvliming on 2017/11/15.
 */

public class CookieUtils {
    private static List<Cookie> cookies;

    /* 返回cookies列表 */
    public static List<Cookie> getCookies() {
        return cookies != null ? cookies : new ArrayList<Cookie>();
    }

    /* 设置cookies列表 */
    public static void setCookies(List<Cookie> cookies) {
        CookieUtils.cookies = cookies;
    }

    /* 存储cookie */
    public static void saveCookie(AsyncHttpClient client, Context context) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        client.setCookieStore(cookieStore);
    }

    /* 得到cookie */
    public static List<Cookie> getCookie(Context context) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        List<Cookie> cookies = cookieStore.getCookies();
        return cookies;
    }

    /* 清除cookie */
    public static void clearCookie(Context context) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);
        cookieStore.clear();
    }
    /**
     * 获取标准 Cookie
     */
    public static String getCookieText(Context context) {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
        List<Cookie> cookies = myCookieStore.getCookies();
        for (Cookie cookie : cookies) {
            Log.d("cookieUtils", cookie.getName() + " = " + cookie.getValue());
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cookies.size(); i++) {
//            Cookie cookie = cookies.get((cookies.size()-1));
            Cookie cookie = cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            String cookiepath = cookie.getPath();
            String cookiedomain = cookie.getDomain();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
                sb.append("domain" + "=");
                sb.append(cookiedomain+";");
                sb.append("path" + "=");
                sb.append(cookiepath + ";");
            }
        }
        Log.e("cookie", sb.toString());
        return sb.toString();
    }
}
