/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.hc.client5.http.impl.classic;

import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import org.apache.hc.client5.http.RouteInfo;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.cookie.Cookie;
import org.apache.hc.client5.http.cookie.CookieOrigin;
import org.apache.hc.client5.http.cookie.CookieSpec;
import org.apache.hc.client5.http.cookie.CookieSpecFactory;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.cookie.StandardCookieSpec;
import org.apache.hc.client5.http.impl.cookie.BasicClientCookie;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.protocol.RequestAddCookies;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpRequestInterceptor;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.config.Lookup;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.net.URIAuthority;
import org.apache.hc.core5.util.Args;
import org.apache.hc.core5.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zaproxy.addon.network.internal.client.apachev5.ZapHttpClientContext;

/**
 * Implementation from {@link RequestAddCookies} but with logic to keep just one cookie header.
 */
public class ZapRequestAddCookies implements HttpRequestInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(ZapRequestAddCookies.class);

    public ZapRequestAddCookies() {
        super();
    }

    @Override
    public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context)
            throws HttpException, IOException {
        Args.notNull(request, "HTTP request");
        Args.notNull(context, "HTTP context");

        final String method = request.getMethod();
        if (Method.CONNECT.isSame(method) || Method.TRACE.isSame(method)) {
            return;
        }

        final HttpClientContext clientContext = HttpClientContext.adapt(context);
        final String exchangeId = clientContext.getExchangeId();

        // Obtain cookie store
        final CookieStore cookieStore = clientContext.getCookieStore();
        if (cookieStore == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} Cookie store not specified in HTTP context", exchangeId);
            }
            return;
        }

        // Obtain the registry of cookie specs
        final Lookup<CookieSpecFactory> registry = clientContext.getCookieSpecRegistry();
        if (registry == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} CookieSpec registry not specified in HTTP context", exchangeId);
            }
            return;
        }

        // Obtain the route (required)
        final RouteInfo route = clientContext.getHttpRoute();
        if (route == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} Connection route not set in the context", exchangeId);
            }
            return;
        }

        final RequestConfig config = clientContext.getRequestConfig();
        String cookieSpecName = config.getCookieSpec();
        if (cookieSpecName == null) {
            cookieSpecName = StandardCookieSpec.STRICT;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("{} Cookie spec selected: {}", exchangeId, cookieSpecName);
        }

        final URIAuthority authority = request.getAuthority();
        String path = request.getPath();
        if (TextUtils.isEmpty(path)) {
            path = "/";
        }
        String hostName = authority != null ? authority.getHostName() : null;
        if (hostName == null) {
            hostName = route.getTargetHost().getHostName();
        }
        int port = authority != null ? authority.getPort() : -1;
        if (port < 0) {
            port = route.getTargetHost().getPort();
        }
        final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, path, route.isSecure());

        // Get an instance of the selected cookie policy
        final CookieSpecFactory factory = registry.lookup(cookieSpecName);
        if (factory == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} Unsupported cookie spec: {}", exchangeId, cookieSpecName);
            }
            return;
        }
        final CookieSpec cookieSpec = factory.create(clientContext);
        // Get all cookies available in the HTTP state
        final List<Cookie> cookies = cookieStore.getCookies();
        // Find cookies matching the given origin
        final List<Cookie> matchedCookies = new ArrayList<>();
        final Instant now = Instant.now();
        boolean expired = false;
        for (final Cookie cookie : cookies) {
            if (!cookie.isExpired(now)) {
                if (cookieSpec.match(cookie, cookieOrigin)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("{} Cookie {} match {}", exchangeId, cookie, cookieOrigin);
                    }
                    matchedCookies.add(cookie);
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("{} Cookie {} expired", exchangeId, cookie);
                }
                expired = true;
            }
        }
        // Per RFC 6265, 5.3
        // The user agent must evict all expired cookies if, at any time, an expired cookie
        // exists in the cookie store
        if (expired) {
            cookieStore.clearExpired(now);
        }
        // Generate Cookie request headers
        if (!matchedCookies.isEmpty()) {
            collectCookies(request, matchedCookies);
            final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
            for (final Header header : headers) {
                request.addHeader(header);
            }
        }

        // Stick the CookieSpec and CookieOrigin instances to the HTTP context
        // so they could be obtained by the response interceptor
        context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
        context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);

        if (clientContext instanceof ZapHttpClientContext) {
            ZapHttpClientContext zapContext = (ZapHttpClientContext) clientContext;
            if (zapContext.getRequestCount() == 1) {
                zapContext.setCookieSetup(cookieStore, registry, route, config, request);
            }
        }
    }

    private static void collectCookies(HttpRequest request, List<Cookie> matchedCookies) {
        if (!request.containsHeader(HttpHeaders.COOKIE)) {
            return;
        }

        HashMap<String, Cookie> allCookies = new LinkedHashMap<>();
        for (Header cookieHeader : request.getHeaders(HttpHeaders.COOKIE)) {
            for (String cookie : cookieHeader.getValue().split(";")) {
                String[] nvp = cookie.split("=", 2);
                String name = nvp[0].trim();
                String value = nvp.length == 1 ? "" : nvp[1].trim();
                allCookies.put(name, new BasicClientCookie(name, value));
            }
        }
        matchedCookies.forEach(e -> allCookies.put(e.getName(), e));
        matchedCookies.clear();
        matchedCookies.addAll(allCookies.values());
        request.removeHeaders(HttpHeaders.COOKIE);
    }
}
