/*
 * Copyright (C) 2014 uPhyca Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.uphyca.idobata.android;

import android.webkit.CookieManager;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Sosuke Masui (masui@uphyca.com)
 */
class CookieHandlerAdapter extends CookieHandler {

    private static final String COOKIE = "Cookie";

    private final CookieManager mCookieManager;

    CookieHandlerAdapter() {
        mCookieManager = CookieManager.getInstance();
    }

    @Override
    public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
        String cookie = mCookieManager.getCookie(uri.toString());
        HashMap<String, List<String>> headers = new HashMap<String, List<String>>();
        if (cookie == null) {
            return headers;
        }
        headers.put(COOKIE, Arrays.asList(cookie));
        return headers;
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
        if (!responseHeaders.containsKey(COOKIE)) {
            return;
        }
        List<String> cookies = responseHeaders.get(COOKIE);
        for (String each : cookies) {
            mCookieManager.setCookie(uri.toString(), each);
        }
    }
}

@@ -999,16 +999,75 @@
 Cookie%22;
+%0A    private static final String SET_COOKIE = %22Set-Cookie%22;
 %0A%0A    pr
@@ -1747,13 +1747,30 @@
     
-if (!
+List%3CString%3E cookie = 
 resp
@@ -1785,30 +1785,24 @@
 ers.
-containsKey(
+get(SET_
 COOKIE)
-) %7B
+;
 %0A   
@@ -1810,19 +1810,29 @@
     
-    return;
+if (cookie == null) %7B
 %0A   
@@ -1840,69 +1840,29 @@
     
-%7D%0A
     
-    List%3CString%3E cookies = responseHeaders.get(COOKIE);
+return;%0A        %7D
 %0A   
@@ -1891,17 +1891,16 @@
 : cookie
-s
 ) %7B%0A    

Fix bugs; CookieHandlerAdapter ignores Set-Cookie header.