/*
 * 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.
 *
 */

package org.apache.skywalking.apm.plugin.jetty.v12.server;

import java.lang.reflect.Method;
import org.apache.skywalking.apm.agent.core.context.CarrierItem;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.Callback;

/**
 * Enhances the core, namespace-neutral {@code org.eclipse.jetty.server.Server#handle(Request, Response,
 * Callback)} — the single top-level entry invoked once per request in Jetty 12. Handling is async, so
 * the entry span is prepared for async in beforeMethod, its synchronous segment ends in afterMethod, and
 * it is finished (with the response status) when the wrapped {@link SwCallback} completes.
 */
public class HandleInterceptor implements InstanceMethodsAroundInterceptor {

    private static final ThreadLocal<SwCallback> HOLDER = new ThreadLocal<SwCallback>();

    @Override
    public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                             MethodInterceptResult result) throws Throwable {
        Request request = (Request) allArguments[0];
        Response response = (Response) allArguments[1];
        Callback callback = (Callback) allArguments[2];

        ContextCarrier contextCarrier = new ContextCarrier();
        HttpFields headers = request.getHeaders();
        CarrierItem next = contextCarrier.items();
        while (next.hasNext()) {
            next = next.next();
            next.setHeadValue(headers.get(next.getHeadKey()));
        }

        HttpURI uri = request.getHttpURI();
        AbstractSpan span = ContextManager.createEntrySpan(uri.getPath(), contextCarrier);
        Tags.URL.set(span, uri.asString());
        Tags.HTTP.METHOD.set(span, request.getMethod());
        span.setComponent(ComponentsDefine.JETTY_SERVER);
        SpanLayer.asHttp(span);
        span.prepareForAsync();

        SwCallback swCallback = new SwCallback(callback, response, span);
        allArguments[2] = swCallback;
        HOLDER.set(swCallback);
    }

    @Override
    public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                              Object ret) throws Throwable {
        SwCallback swCallback = HOLDER.get();
        HOLDER.remove();
        ContextManager.stopSpan();
        // ret == true: handled; the wrapped callback fires on response completion and finishes the span.
        // ret == false: not handled — Jetty writes 404 on the original callback, bypassing ours.
        // ret == null: handle() threw (see handleMethodException) — Jetty writes 500.
        // For the latter two the wrapped callback never fires and the status is written only after
        // handle() returns, so finish here with the status Jetty's contract guarantees.
        if (swCallback != null && !Boolean.TRUE.equals(ret)) {
            swCallback.finishWithStatus(ret == null ? 500 : 404);
        }
        return ret;
    }

    @Override
    public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
                                      Class<?>[] argumentsTypes, Throwable t) {
        AbstractSpan span = ContextManager.activeSpan();
        span.log(t);
        span.errorOccurred();
    }
}
