package ru.yandex.webmaster3.storage.events.utils;

import org.joda.time.DateTime;

/**
 * @author avhaliullin
 */
public class BatchIdUtils {
    public static final int SAFETY_WINDOW = 10 * 1000;
    public static final int BATCH_SIZE_MILLIS = 1000 * 60;

    public static boolean isSafeToWrite(long millis) {
        return millis >= millisToBatchId(System.currentTimeMillis());
    }

    public static long getNextBatch(long batchId) {
        return millisToBatchId(batchId) + BATCH_SIZE_MILLIS;
    }

    public static long getLastSafeBatch() {
        return millisToBatchId(System.currentTimeMillis() - SAFETY_WINDOW) - BATCH_SIZE_MILLIS;
    }

    public static long millisToBatchId(long millis) {
        return (millis / BATCH_SIZE_MILLIS) * BATCH_SIZE_MILLIS;
    }

    public static long dateTimeToBatchId(DateTime time) {
        return millisToBatchId(time.getMillis());
    }

    public static long waitSafeBatch(long batchId) throws InterruptedException {
        if (batchId > getLastSafeBatch()) {
            Thread.sleep((batchId - System.currentTimeMillis()) + BATCH_SIZE_MILLIS + SAFETY_WINDOW);
        }
        return batchId;
    }
}
