package com.sipai.jspatrol.utils.okHttpCookie;

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

import com.sipai.jspatrol.Application.App;

import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * created by lvliming on 2019/9/16
 */
public class CookiesManager implements CookieJar {

    private final PersistentCookieStore cookieStore = new PersistentCookieStore(App.getInstance());

    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
            }
        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url);
        return cookies;
    }

    /* 得到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.removeAll();
    }

    /**
     * 获取标准 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.name() + " = " + cookie.value());
        }
        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.name();
            String cookieValue = cookie.value();
            String cookiepath = cookie.path();
            String cookiedomain = cookie.domain();
            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();
    }
}
