/*
 *  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.groovy.contracts;

import org.apache.groovy.contracts.util.Validate;

import java.util.NavigableMap;
import java.util.TreeMap;

/**
 * <p>
 * A violation tracker is used to keep a list of pre-, post-condition or class-invariant
 * violations in chronological order. This is necessary to evaluate all parts of a pre- or postcondition, and still
 * being able to rethrow assertion errors.
 * </p>
 */
public class ViolationTracker {

    /**
     * Stores the tracker bound to the current thread while a contract is being evaluated.
     */
    public static final ThreadLocal<ViolationTracker> INSTANCE = new ThreadLocal<>();

    /**
     * Installs a fresh tracker for the current thread.
     */
    public static void init() {
        INSTANCE.set(new ViolationTracker());
    }

    /**
     * Removes the tracker associated with the current thread.
     */
    public static void deinit() {
        INSTANCE.remove();
    }

    /**
     * Indicates whether the current thread has recorded at least one violation.
     *
     * @return {@code true} if a violation has been tracked for the current thread
     */
    public static boolean violationsOccurred() {
        return INSTANCE.get().hasViolations();
    }

    /**
     * Rethrows the earliest recorded violation for the current thread.
     */
    public static void rethrowFirst() {
        throw INSTANCE.get().first();
    }

    /**
     * Rethrows the most recently recorded violation for the current thread.
     */
    public static void rethrowLast() {
        throw INSTANCE.get().last();
    }

    private final NavigableMap<Long, AssertionViolation> violations = new TreeMap<>();

    /**
     * Records a newly observed assertion violation in encounter order.
     *
     * @param assertionViolation the violation to store
     */
    public void track(final AssertionViolation assertionViolation) {
        Validate.notNull(assertionViolation);

        violations.put(System.nanoTime(), assertionViolation);
    }

    /**
     * Indicates whether this tracker currently contains any violations.
     *
     * @return {@code true} if at least one violation has been recorded
     */
    public boolean hasViolations() {
        return !violations.isEmpty();
    }

    /**
     * Returns the earliest recorded violation.
     *
     * @return the first violation in encounter order
     */
    public AssertionViolation first() {
        return violations.firstEntry().getValue();
    }

    /**
     * Returns the most recently recorded violation.
     *
     * @return the last violation in encounter order
     */
    public AssertionViolation last() {
        return violations.lastEntry().getValue();
    }
}
