/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * 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 com.fsck.k9;


import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;

import timber.log.Timber;


/**
 * This class used to "throttle" a flow of events.
 *
 * When {@link #onEvent()} is called, it calls the callback in a certain timeout later.
 * Initially {@link #minTimeout} is used as the timeout, but if it gets multiple {@link #onEvent}
 * calls in a certain amount of time, it extends the timeout, until it reaches {@link #maxTimeout}.
 *
 * This class is primarily used to throttle content changed events.
 */
public class Throttle {
    private static final int TIMEOUT_EXTEND_INTERVAL = 500;

    private static Timer TIMER = new Timer();

    private final Clock clock;
    private final Timer timer;

    private final String name;
    private final Handler handler;
    private final Runnable callback;

    private final int minTimeout;
    private final int maxTimeout;
    private int currentTimeout;

    /** When {@link #onEvent()} was last called. */
    private long lastEventTime;

    private MyTimerTask runningTimerTask;

    /** Constructor that takes custom timeout */
    public Throttle(String name, Runnable callback, Handler handler,int minTimeout,
            int maxTimeout) {
        this(name, callback, handler, minTimeout, maxTimeout, Clock.INSTANCE, TIMER);
    }

    /** Constructor for tests */
    private Throttle(String name, Runnable callback, Handler handler, int minTimeout,
            int maxTimeout, Clock clock, Timer timer) {
        if (maxTimeout < minTimeout) {
            throw new IllegalArgumentException();
        }
        this.name = name;
        this.callback = callback;
        this.clock = clock;
        this.timer = timer;
        this.handler = handler;
        this.minTimeout = minTimeout;
        this.maxTimeout = maxTimeout;
        currentTimeout = this.minTimeout;
    }

    private boolean isCallbackScheduled() {
        return runningTimerTask != null;
    }

    public void cancelScheduledCallback() {
        if (runningTimerTask != null) {
            Timber.d("Throttle: [%s] %s", name, "Canceling scheduled callback");
            runningTimerTask.cancel();
            runningTimerTask = null;
        }
    }

    private void updateTimeout() {
        final long now = clock.getTime();
        if ((now - lastEventTime) <= TIMEOUT_EXTEND_INTERVAL) {
            currentTimeout *= 2;
            if (currentTimeout >= maxTimeout) {
                currentTimeout = maxTimeout;
            }
            Timber.d("Throttle: [%s] %s", name, "Timeout extended " + currentTimeout);
        } else {
            currentTimeout = minTimeout;
            Timber.d("Throttle: [%s] %s", name, "Timeout reset to " + currentTimeout);
        }

        lastEventTime = now;
    }

    public void onEvent() {
        Timber.d("Throttle: [%s] %s", name, "onEvent");

        updateTimeout();

        if (isCallbackScheduled()) {
            Timber.d("Throttle: [%s] %s", name, "    callback already scheduled");
        } else {
            Timber.d("Throttle: [%s] %s", name, "    scheduling callback");
            runningTimerTask = new MyTimerTask();
            timer.schedule(runningTimerTask, currentTimeout);
        }
    }

    /**
     * Timer task called on timeout,
     */
    private class MyTimerTask extends TimerTask {
        private boolean mCanceled;

        @Override
        public void run() {
            handler.post(new HandlerRunnable());
        }

        @Override
        public boolean cancel() {
            mCanceled = true;
            return super.cancel();
        }

        private class HandlerRunnable implements Runnable {
            @Override
            public void run() {
                runningTimerTask = null;
                if (!mCanceled) { // This check has to be done on the UI thread.
                    Timber.d("Throttle: [%s] %s", name, "Kicking callback");
                    callback.run();
                }
            }
        }
    }
}

@@ -2709,28 +2709,16 @@
 e: %5B%25s%5D 
-%25s%22, name, %22
 Cancelin
@@ -2730,32 +2730,38 @@
 eduled callback%22
+, name
 );%0A            r
@@ -3154,36 +3154,24 @@
 ottle: %5B%25s%5D 
-%25s%22, name, %22
 Timeout exte
@@ -3175,19 +3175,26 @@
 xtended 
-%22 +
+%25d%22, name,
  current
@@ -3298,28 +3298,16 @@
 e: %5B%25s%5D 
-%25s%22, name, %22
 Timeout 
@@ -3319,11 +3319,18 @@
  to 
-%22 +
+%25d%22, name,
  cur
@@ -3455,28 +3455,16 @@
 %25s%5D 
-%25s%22, name, %22
 onEvent%22
 );%0A%0A
@@ -3459,16 +3459,22 @@
 onEvent%22
+, name
 );%0A%0A    
@@ -3565,36 +3565,24 @@
 ottle: %5B%25s%5D 
-%25s%22, name, %22
     callback
@@ -3600,16 +3600,22 @@
 heduled%22
+, name
 );%0A     
@@ -3663,28 +3663,16 @@
 e: %5B%25s%5D 
-%25s%22, name, %22
     sche
@@ -3679,32 +3679,38 @@
 duling callback%22
+, name
 );%0A            r
@@ -4483,20 +4483,8 @@
 %25s%5D 
-%25s%22, name, %22
 Kick
@@ -4496,16 +4496,22 @@
 allback%22
+, name
 );%0A     

Clean up Timber string format arguments