package cn.axzo.msg.center.message.service.todo.cache;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author yanglin
 */
@Slf4j
@RequiredArgsConstructor
class CacheMetric {

    private final String name;
    private final DateTime createAt = DateTime.now();
    private final AtomicLong hitCount = new AtomicLong();
    private final AtomicLong missCount = new AtomicLong();

    void incrHitCount() {
        hitCount.incrementAndGet();
    }

    void incrMissCount() {
        missCount.incrementAndGet();
    }

    /**
     * 大概统计一下, 不是100%准确
     */
    void print() {
        DateTime printAt = DateTime.now();
        String pattern = "yyyy-MM-dd HH:mm:ss";

        long hitCount = this.hitCount.get();
        long missCount = this.missCount.get();
        long totalAccesses = hitCount + missCount;
        double hitRate = totalAccesses == 0 ? 0 : ((double) hitCount / totalAccesses) * 100;

        log.info("CacheMetric[{}]: {} ~ {}, hitCount={}, missCount={}, hitRate={}%",
                name,
                createAt.toString(pattern), printAt.toString(pattern),
                hitCount, missCount, String.format("%.2f", hitRate));
    }

}