// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;

import com.google.inject.AbstractModule;
import com.google.inject.Injector;
import com.yahoo.jdisc.AbstractResource;
import com.yahoo.jdisc.SharedResource;
import com.yahoo.jdisc.application.BindingSet;
import com.yahoo.jdisc.application.BindingSetSelector;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.ResourcePool;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.BindingSetNotFoundException;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.service.NoBindingSetSelectedException;
import com.yahoo.jdisc.service.ServerProvider;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;

/**
 * @author Simon Thoresen
 * @author bjorncs
 */
public class ActiveContainer extends AbstractResource implements CurrentContainer {

    private static final Logger log = Logger.getLogger(ActiveContainer.class.getName());

    private final ContainerTermination termination;
    private final Injector guiceInjector;
    private final Iterable<ServerProvider> serverProviders;
    private final ResourcePool resourceReferences = new ResourcePool();
    private final Map<String, BindingSet<RequestHandler>> serverBindings;
    private final Map<String, BindingSet<RequestHandler>> clientBindings;
    private final BindingSetSelector bindingSetSelector;
    private final TimeoutManagerImpl timeoutMgr;
    private final Destructor destructor;

    public ActiveContainer(ContainerBuilder builder) {
        serverProviders = builder.serverProviders().activate();
        serverProviders.forEach(resourceReferences::retain);
        serverBindings = builder.activateServerBindings();
        serverBindings.forEach(
                (ignoredName, bindingSet) -> bindingSet.forEach(
                        binding -> resourceReferences.retain(binding.getValue())));
        clientBindings = builder.activateClientBindings();
        clientBindings.forEach(
                (ignoredName, bindingSet) -> bindingSet.forEach(
                        binding -> resourceReferences.retain(binding.getValue())));
        bindingSetSelector = builder.getInstance(BindingSetSelector.class);
        timeoutMgr = builder.getInstance(TimeoutManagerImpl.class);
        timeoutMgr.start();
        builder.guiceModules().install(new AbstractModule() {

            @Override
            protected void configure() {
                bind(TimeoutManagerImpl.class).toInstance(timeoutMgr);
            }
        });
        guiceInjector = builder.guiceModules().activate();
        termination = new ContainerTermination(builder.appContext());
        destructor = new Destructor(resourceReferences, timeoutMgr, termination);
    }

    @Override
    protected void destroy() {
        boolean alreadyDestructed = destructor.destruct();
        if (alreadyDestructed) {
            throw new IllegalStateException(
                    "Already destructed! This should not occur unless destroy have been called directly!");
        }
    }

    /**
     * Make this instance retain a reference to the resource until it is destroyed.
     */
    void retainReference(SharedResource resource) {
        resourceReferences.retain(resource);
    }

    public ContainerTermination shutdown() {
        return termination;
    }

    public Injector guiceInjector() {
        return guiceInjector;
    }

    public Iterable<ServerProvider> serverProviders() {
        return serverProviders;
    }

    public Map<String, BindingSet<RequestHandler>> serverBindings() {
        return serverBindings;
    }

    public BindingSet<RequestHandler> serverBindings(String setName) {
        return serverBindings.get(setName);
    }

    public Map<String, BindingSet<RequestHandler>> clientBindings() {
        return clientBindings;
    }

    public BindingSet<RequestHandler> clientBindings(String setName) {
        return clientBindings.get(setName);
    }

    TimeoutManagerImpl timeoutManager() {
        return timeoutMgr;
    }

    @Override
    public ContainerSnapshot newReference(URI uri) {
        String name = bindingSetSelector.select(uri);
        if (name == null) {
            throw new NoBindingSetSelectedException(uri);
        }
        BindingSet<RequestHandler> serverBindings = serverBindings(name);
        BindingSet<RequestHandler> clientBindings = clientBindings(name);
        if (serverBindings == null || clientBindings == null) {
            throw new BindingSetNotFoundException(name);
        }
        return new ContainerSnapshot(this, serverBindings, clientBindings);
    }

    // TODO Rewrite to use cleaners after Java 9 migration
    @Override
    protected void finalize() throws Throwable {
        boolean alreadyDestructed = destructor.destruct();
        if (!alreadyDestructed) {
            log.severe(toString() + " was not correctly cleaned up " +
                               "because of a resource leak or invalid use of reference counting.");
        }
        super.finalize();
    }

    // NOTE: An instance of this class must never contain a reference to the outer class (ActiveContainer).
    private static class Destructor {
        private final ResourcePool resourceReferences;
        private final TimeoutManagerImpl timeoutMgr;
        private final ContainerTermination termination;
        private final AtomicBoolean done = new AtomicBoolean();

        private Destructor(ResourcePool resourceReferences,
                           TimeoutManagerImpl timeoutMgr,
                           ContainerTermination termination) {
            this.resourceReferences = resourceReferences;
            this.timeoutMgr = timeoutMgr;
            this.termination = termination;
        }

        boolean destruct() {
            boolean alreadyDestructed = this.done.getAndSet(true);
            if (!alreadyDestructed) {
                resourceReferences.release();
                timeoutMgr.shutdown();
                termination.run();
            }
            return alreadyDestructed;
        }
    }
}

@@ -13,9 +13,9 @@
  201
-7
+8
  Yah
@@ -815,91 +815,8 @@
 Map;
-%0Aimport java.util.concurrent.atomic.AtomicBoolean;%0Aimport java.util.logging.Logger;
 %0A%0A/*
@@ -955,98 +955,8 @@
  %7B%0A%0A
-    private static final Logger log = Logger.getLogger(ActiveContainer.class.getName());%0A%0A
     
@@ -1434,49 +1434,8 @@
 Mgr;
-%0A    private final Destructor destructor;
 %0A%0A  
@@ -2624,392 +2624,176 @@
     
-    destructor = new Destructor(resourceReferences, timeoutMgr, termination);%0A    %7D%0A%0A    @Override%0A    protected void destroy() %7B%0A        boolean alreadyDestructed = destructor.destruct();%0A        if (alreadyDestructed) %7B%0A            throw new IllegalStateException(%0A                    %22Already destructed! This should not occur unless destroy have been called directly!%22);%0A        %7D
+%7D%0A%0A    @Override%0A    protected void destroy() %7B%0A        resourceReferences.release();%0A        timeoutMgr.shutdown();%0A        termination.run();%0A        super.destroy();
 %0A   
@@ -4369,1468 +4369,6 @@
  %7D%0A%0A
-    // TODO Rewrite to use cleaners after Java 9 migration%0A    @Override%0A    protected void finalize() throws Throwable %7B%0A        boolean alreadyDestructed = destructor.destruct();%0A        if (!alreadyDestructed) %7B%0A            log.severe(toString() + %22 was not correctly cleaned up %22 +%0A                               %22because of a resource leak or invalid use of reference counting.%22);%0A        %7D%0A        super.finalize();%0A    %7D%0A%0A    // NOTE: An instance of this class must never contain a reference to the outer class (ActiveContainer).%0A    private static class Destructor %7B%0A        private final ResourcePool resourceReferences;%0A        private final TimeoutManagerImpl timeoutMgr;%0A        private final ContainerTermination termination;%0A        private final AtomicBoolean done = new AtomicBoolean();%0A%0A        private Destructor(ResourcePool resourceReferences,%0A                           TimeoutManagerImpl timeoutMgr,%0A                           ContainerTermination termination) %7B%0A            this.resourceReferences = resourceReferences;%0A            this.timeoutMgr = timeoutMgr;%0A            this.termination = termination;%0A        %7D%0A%0A        boolean destruct() %7B%0A            boolean alreadyDestructed = this.done.getAndSet(true);%0A            if (!alreadyDestructed) %7B%0A                resourceReferences.release();%0A                timeoutMgr.shutdown();%0A                termination.run();%0A            %7D%0A            return alreadyDestructed;%0A        %7D%0A    %7D%0A
 %7D%0A

Remove finalizer() from ActiveContainer