/*
 * 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.jackrabbit.oak.plugins.segment.file;

import static java.lang.System.currentTimeMillis;

import java.io.Closeable;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A small wrapper around the Thread class that periodically calls a runnable.
 * Please note the Runnable.run() method is not supposed to loop itself, instead
 * it should just do one operation. This class calls Runnable.run() repeatedly.
 * This class also measures and logs the time taken by the Runnable.run()
 * method.
 */
class BackgroundThread extends Thread implements Closeable {

    /** Logger instance */
    private static final Logger log =
            LoggerFactory.getLogger(BackgroundThread.class);

    private final String name;

    private final long interval;

    private boolean alive = true;

    private long iterations = 0;

    private long sumDuration = 0;

    private long maxDuration = 0;

    private BackgroundThread(String name, long interval, Runnable target) {
        super(target, name);

        this.name = name;
        this.interval = interval;

        setDaemon(true);
        setPriority(MIN_PRIORITY);
    }

    /**
     * Run a {@code task} in an regular {@code interval} in the background
     * (i.e. {@link Thread#MIN_PRIORITY}.
     * @param name       name of the thread
     * @param interval   interval in milliseconds
     * @param task       task to run
     * @return  the {@code BackgroundThread} instance running {@code task}.
     */
    public static BackgroundThread run(String name, long interval, Runnable task) {
        BackgroundThread t = new BackgroundThread(name, interval, task);
        t.start();
        return t;
    }

    @Override
    public void run() {
        try {
            while (waitUntilNextIteration()) {
                setName(name + ", active since " + new Date()
                        + ", previous max duration " + maxDuration + "ms");

                long start = currentTimeMillis();
                super.run();
                long duration = currentTimeMillis() - start;

                iterations++;
                sumDuration += duration;
                maxDuration = Math.max(maxDuration, duration);

                // make execution statistics visible in thread dumps
                setName(name
                        + ", avg " + (sumDuration / iterations) + "ms"
                        + ", max " + maxDuration + "ms");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error(name + " interrupted", e);
        } catch (RuntimeException e) {
            log.error("Unhandled exception in background thread", e);
            throw e;
        }
    }

    void trigger() {
        trigger(false);
    }

    @Override
    public void close() {
        try {
            trigger(true);
            join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error(name + " join interrupted", e);
        }
    }

    private synchronized void trigger(boolean close) {
        if (close) {
            alive = false;
        }
        notify();
    }

    private synchronized boolean waitUntilNextIteration()
            throws InterruptedException {
        if (alive) {
            if (interval < 0) {
                wait();
            } else {
                wait(interval);
            }
        }
        return alive;
    }

}
