/**
 * ******************************************************************************
 *  Copyright Fujitsu.
 *
 *  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.
 * *****************************************************************************
 *
 *  NIFCLOUD SDK for Java
 *
 */
package com.nifty.cloud.sdk.tools;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.CharArrayBuffer;

import java.util.Locale;

/**
 * HTTPヘッダユーティリティ。<br />
 * HTTPヘッダに関する変換を行います。
 */
public class HttpHeaderUtils {
    /**
     * 指定した名前のヘッダを取得します。
     * 同じ名前のヘッダが複数ある場合はRFC 2616に従い","で連結します。
     *
     * @param response HTTPレスポンス
     * @param name ヘッダ名
     * @return 連結したHeader または{@code null}(指定された名前のヘッダがない場合)
     */
    /*
     * from org.apache.http.message.HeaderGroup#getCondensedHeader()
     * https://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/message/HeaderGroup.html#getCondensedHeader%28java.lang.String%29
     *
     * Gets a header representing all of the header values with the given name.
     * If more that one header with the given name exists the values will be
     * combined with a "," as per RFC 2616.
     *
     * <p>Header name comparison is case insensitive.
     *
     * @param response http response
     * @param name the name of the header(s)
     * @return a header with a condensed value or {@code null} if no
     * headers by the given name are present
     */
    public static Header getCondensedHeader(final HttpResponse response, final String name) {
        final Header[] hdrs = response.getHeaders(name);

        if (hdrs.length == 0) {
            return null;
        } else if (hdrs.length == 1) {
            return hdrs[0];
        } else {
            final CharArrayBuffer valueBuffer = new CharArrayBuffer(128);
            valueBuffer.append(hdrs[0].getValue());
            for (int i = 1; i < hdrs.length; i++) {
                valueBuffer.append(", ");
                valueBuffer.append(hdrs[i].getValue());
            }

            return new BasicHeader(name.toLowerCase(Locale.ROOT), valueBuffer.toString());
        }
    }
}
