// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.clients;

import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.handler.threadpool.ContainerThreadpoolConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.ContainerThreadpool;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
import com.yahoo.vespa.model.container.component.UserBindingPattern;

import java.util.Collection;
import java.util.Collections;

/**
 * @author Einar M R Rosenvinge
 * @author bjorncs
 */
public class ContainerDocumentApi {

    public static final String DOCUMENT_V1_PREFIX = "/document/v1";

    public ContainerDocumentApi(ContainerCluster<?> cluster, Options options) {
        var executor = new Threadpool("feedapi-handler", cluster, options.feedApiThreadpoolOptions);
        cluster.addComponent(executor);
        addRestApiHandler(cluster, options, executor);
        addFeedHandler(cluster, options, executor);
    }

    private static void addFeedHandler(ContainerCluster<?> cluster, Options options, Threadpool executor) {
        String bindingSuffix = ContainerCluster.RESERVED_URI_PREFIX + "/feedapi";
        var handler = newVespaClientHandler("com.yahoo.vespa.http.server.FeedHandler", bindingSuffix, options);
        cluster.addComponent(handler);
        handler.inject(executor);
    }


    private static void addRestApiHandler(ContainerCluster<?> cluster, Options options, Threadpool executor) {
        var handler = newVespaClientHandler("com.yahoo.document.restapi.resource.DocumentV1ApiHandler", DOCUMENT_V1_PREFIX + "/*", options);
        cluster.addComponent(handler);
        handler.inject(executor);

        // We need to include a dummy implementation of the previous restapi handler (using the same class name).
        // The internal legacy test framework requires that the name of the old handler is listed in /ApplicationStatus.
        var oldHandlerDummy = handlerComponentSpecification("com.yahoo.document.restapi.resource.RestApi");
        cluster.addComponent(oldHandlerDummy);
    }

    private static Handler<AbstractConfigProducer<?>> newVespaClientHandler(
            String componentId,
            String bindingSuffix,
            Options options) {
        Handler<AbstractConfigProducer<?>> handler = handlerComponentSpecification(componentId);
        if (options.bindings.isEmpty()) {
            handler.addServerBindings(
                    SystemBindingPattern.fromHttpPath(bindingSuffix),
                    SystemBindingPattern.fromHttpPath(bindingSuffix + '/'));
        } else {
            for (String rootBinding : options.bindings) {
                String pathWithoutLeadingSlash = bindingSuffix.substring(1);
                handler.addServerBindings(
                        UserBindingPattern.fromPattern(rootBinding + pathWithoutLeadingSlash),
                        UserBindingPattern.fromPattern(rootBinding + pathWithoutLeadingSlash + '/'));
            }
        }
        return handler;
    }

    private static Handler<AbstractConfigProducer<?>> handlerComponentSpecification(String className) {
        return new Handler<>(new ComponentModel(
                BundleInstantiationSpecification.getFromStrings(className, null, "vespaclient-container-plugin"), ""));
    }

    public static final class Options {
        private final Collection<String> bindings;
        private final ContainerThreadpool.UserOptions feedApiThreadpoolOptions;

        public Options(Collection<String> bindings, ContainerThreadpool.UserOptions feedApiThreadpoolOptions) {
            this.bindings = Collections.unmodifiableCollection(bindings);
            this.feedApiThreadpoolOptions = feedApiThreadpoolOptions;
        }
    }

    private static class Threadpool extends ContainerThreadpool {

        private final ContainerCluster<?> cluster;

        Threadpool(String name,
                   ContainerCluster<?> cluster,
                   ContainerThreadpool.UserOptions threadpoolOptions) {
            super(name, threadpoolOptions);
            this.cluster = cluster;
        }

        @Override
        public void getConfig(ContainerThreadpoolConfig.Builder builder) {
            super.getConfig(builder);

            // User options overrides below configuration
            if (hasUserOptions()) return;
            builder.maxThreads(-4).minThreads(-4).queueSize(500);
        }
    }

}

@@ -1020,149 +1020,8 @@
 ) %7B%0A
-        var executor = new Threadpool(%22feedapi-handler%22, cluster, options.feedApiThreadpoolOptions);%0A        cluster.addComponent(executor);%0A
     
@@ -1054,34 +1054,24 @@
 ter, options
-, executor
 );%0A        a
@@ -1104,18 +1104,8 @@
 ions
-, executor
 );%0A 
@@ -1193,37 +1193,16 @@
  options
-, Threadpool executor
 ) %7B%0A    
@@ -1434,37 +1434,178 @@
 r);%0A        
-handler.injec
+var executor = new Threadpool(%22feedapi-handler%22, cluster, options.feedApiThreadpoolOptions);%0A        handler.inject(executor);%0A        handler.addComponen
 t(executor);
@@ -1703,29 +1703,8 @@
 ions
-, Threadpool executor
 ) %7B%0A
@@ -1886,42 +1886,8 @@
 er);
-%0A        handler.inject(executor);
 %0A%0A  

Revert "Inject feed-handler thread pool to /doc/v1"