package com.eactive.eai.custom.alarm.policy;

import com.eactive.eai.custom.alarm.event.AlarmEvent;
import com.eactive.eai.custom.alarm.key.AlarmKey;

public abstract class AlarmPolicy {

    private AlarmKey alarmKey;

    private int thresholdCount;

    private long timeWindowMs;

    protected AlarmPolicy(Builder<?> builder) {
	this.alarmKey = builder.alarmKey;
	this.thresholdCount = builder.thresholdCount;
	this.timeWindowMs = builder.timeWindowMs;
    }

    public AlarmKey getAlarmKey() {
	return alarmKey;
    }

    public int getThresholdCount() {
	return thresholdCount;
    }

    public long getTimeWindowMs() {
	return timeWindowMs;
    }

    public abstract boolean isAlarmTriggered(AlarmEvent event);
    

    public boolean hasElapsed(long baseTimeMs) {

	return System.currentTimeMillis() - baseTimeMs >= timeWindowMs;

    }

    public boolean hasExceededLimit(long count) {
	return count >= thresholdCount;
    }

    public abstract static class Builder<T extends Builder<T>> {

	private AlarmKey alarmKey;
	private int thresholdCount;
	private long timeWindowMs;

	public T alarmKey(AlarmKey alarmKey) {
	    this.alarmKey = alarmKey;
	    return self();
	}

	public T thresholdCount(int thresholdCount) {
	    this.thresholdCount = thresholdCount;
	    return self();
	}

	public T timeWindowMs(long timeWindowMs) {
	    this.timeWindowMs = timeWindowMs;
	    return self();
	}

	protected abstract T self();

	abstract AlarmPolicy build();
    }

}