/*
 * 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.dubbo.metrics.aggregate;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

/**
 * Wrapper around Counter like Long and Integer.
 */
public class TimeWindowCounter {

    private final LongAdderSlidingWindow slidingWindow;

    public TimeWindowCounter(int bucketNum, long timeWindowSeconds) {
        this.slidingWindow = new LongAdderSlidingWindow(bucketNum, TimeUnit.SECONDS.toMillis(timeWindowSeconds));
    }

    public double get() {
        double result = 0.0;
        List<LongAdder> windows = this.slidingWindow.values();
        for (LongAdder window : windows) {
            result += window.sum();
        }
        return result;
    }

    public long bucketLivedSeconds() {
        return TimeUnit.MILLISECONDS.toSeconds(
                this.slidingWindow.values().size() * this.slidingWindow.getPaneIntervalInMs());
    }

    public long bucketLivedMillSeconds() {
        return this.slidingWindow.getIntervalInMs()
                - (System.currentTimeMillis() - this.slidingWindow.currentPane().getEndInMs());
    }

    public void increment() {
        this.increment(1L);
    }

    public void increment(Long step) {
        this.slidingWindow.currentPane().getValue().add(step);
    }

    public void decrement() {
        this.decrement(1L);
    }

    public void decrement(Long step) {
        this.slidingWindow.currentPane().getValue().add(-step);
    }

    /**
     * Sliding window of type LongAdder.
     */
    private static class LongAdderSlidingWindow extends SlidingWindow<LongAdder> {

        public LongAdderSlidingWindow(int sampleCount, long intervalInMs) {
            super(sampleCount, intervalInMs);
        }

        @Override
        public LongAdder newEmptyValue(long timeMillis) {
            return new LongAdder();
        }

        @Override
        protected Pane<LongAdder> resetPaneTo(final Pane<LongAdder> pane, long startTime) {
            pane.setStartInMs(startTime);
            pane.getValue().reset();
            return pane;
        }
    }
}
