/*
 * Copyright 2016 Timothy Brooks
 *
 * 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.
 *
 */

package net.uncontended.precipice.pattern;

import net.uncontended.precipice.*;
import net.uncontended.precipice.concurrent.NewEventual;
import net.uncontended.precipice.concurrent.PrecipicePromise;
import net.uncontended.precipice.metrics.ActionMetrics;
import net.uncontended.precipice.metrics.LatencyMetrics;

import java.util.concurrent.atomic.AtomicReference;

public class PatternController<T extends Enum<T> & Result> {
    private final ActionMetrics<T> actionMetrics;
    private final LatencyMetrics<T> latencyMetrics;
    private final String name;
    private final AtomicReference<NewController<T>[]> children;
    private volatile boolean isShutdown = false;

    public PatternController(String name, PatternControllerProperties<T> properties) {
        this(name, properties.actionMetrics(), properties.latencyMetrics());
    }

    public PatternController(String name, ActionMetrics<T> actionMetrics, LatencyMetrics<T> latencyMetrics) {
        this.actionMetrics = actionMetrics;
        this.latencyMetrics = latencyMetrics;
        this.name = name;
        children = new AtomicReference<>((NewController<T>[]) new NewController[0]);
    }

    public String getName() {
        return name;
    }

    public ActionMetrics<T> getActionMetrics() {
        return actionMetrics;
    }

    public LatencyMetrics<T> getLatencyMetrics() {
        return latencyMetrics;
    }

    public void ensureNotShutdown() {
        if (isShutdown) {
            throw new IllegalStateException("Service has been shutdown.");
        }
    }

    public <R> PrecipicePromise<T, R> getPromise() {
        ensureNotShutdown();
        long startTime = System.nanoTime();
        if (null != null) {
            actionMetrics.incrementRejectionCount(null, startTime);
            throw new RejectedActionException(null);
        }

        NewEventual<T, R> promise = new NewEventual<>(startTime);
        promise.internalOnComplete(new PrecipiceFunction<T, PerformingContext>() {
            @Override
            public void apply(T status, PerformingContext eventual) {
                long endTime = System.nanoTime();
                actionMetrics.incrementMetricCount(status);
                latencyMetrics.recordLatency(status, endTime - eventual.startNanos(), endTime);
            }
        });
        return promise;
    }

    public <R> PrecipicePromise<T, R> getPromise(NewController<T>[] controllers) {
        ensureNotShutdown();
        long startTime = System.nanoTime();

        NewController<T> controllerToUse = null;
        for (NewController<T> controller : controllers) {
            Rejected rejected = controller.acquirePermitOrGetRejectedReason();
            if (rejected != null) {
                controllerToUse = controller;
            }
        }
        if (controllerToUse != null) {
            NewEventual<T, R> promise = new NewEventual<>(startTime);
            promise.internalOnComplete(new PrecipiceFunction<T, PerformingContext>() {
                @Override
                public void apply(T status, PerformingContext eventual) {
                    long endTime = System.nanoTime();
                    actionMetrics.incrementMetricCount(status);
                    latencyMetrics.recordLatency(status, endTime - eventual.startNanos(), endTime);
                }
            });
            return promise;
        } else {
            actionMetrics.incrementRejectionCount(null, startTime);
            throw new RejectedActionException(null);
        }
    }

    public NewController<T>[] getChildControllers() {
        return children.get();
    }

    public void shutdown() {
        isShutdown = true;
    }
}

@@ -2181,27 +2181,73 @@
 e%3CT, R%3E 
-getPromise(
+acquirePermitAndGetPromise(NewController%3CT%3E%5B%5D controllers
 ) %7B%0A    
@@ -2319,33 +2319,396 @@
 ();%0A
-        if (null != null)
+%0A        NewController%3CT%3E controllerToUse = null;%0A        for (NewController%3CT%3E controller : controllers) %7B%0A            Rejected rejected = controller.acquirePermitOrGetRejectedReason();%0A            if (rejected != null) %7B%0A                controllerToUse = controller;%0A            %7D%0A        %7D%0A        if (controllerToUse != null) %7B%0A            return getPromise(startTime);%0A        %7D else
  %7B%0A 
@@ -2833,24 +2833,97 @@
 ;%0A        %7D%0A
+    %7D%0A%0A    public %3CR%3E PrecipicePromise%3CT, R%3E getPromise(long startTime) %7B
 %0A        New
@@ -3419,1188 +3419,8 @@
  %7D%0A%0A
-    public %3CR%3E PrecipicePromise%3CT, R%3E getPromise(NewController%3CT%3E%5B%5D controllers) %7B%0A        ensureNotShutdown();%0A        long startTime = System.nanoTime();%0A%0A        NewController%3CT%3E controllerToUse = null;%0A        for (NewController%3CT%3E controller : controllers) %7B%0A            Rejected rejected = controller.acquirePermitOrGetRejectedReason();%0A            if (rejected != null) %7B%0A                controllerToUse = controller;%0A            %7D%0A        %7D%0A        if (controllerToUse != null) %7B%0A            NewEventual%3CT, R%3E promise = new NewEventual%3C%3E(startTime);%0A            promise.internalOnComplete(new PrecipiceFunction%3CT, PerformingContext%3E() %7B%0A                @Override%0A                public void apply(T status, PerformingContext eventual) %7B%0A                    long endTime = System.nanoTime();%0A                    actionMetrics.incrementMetricCount(status);%0A                    latencyMetrics.recordLatency(status, endTime - eventual.startNanos(), endTime);%0A                %7D%0A            %7D);%0A            return promise;%0A        %7D else %7B%0A            actionMetrics.incrementRejectionCount(null, startTime);%0A            throw new RejectedActionException(null);%0A        %7D%0A    %7D%0A%0A
     

Add new methods to pattern controller