package ru.yandex.webmaster3.storage.util.clickhouse2.batch;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tsyplyaev
 */
public abstract class Batch<T extends BatchEntry> {
    private final int sizeMB;
    private long currentSizeBytes = 0;
    private List<T> entries = new ArrayList<>();

    public Batch(int sizeMB) {
        this.sizeMB = sizeMB;
    }

    public void add(T batchEntry) throws Exception {
        entries.add(batchEntry);
        currentSizeBytes += batchEntry.getSizeBytes();
        if (currentSizeBytes / 1000000 >= sizeMB) {
            flush();
        }
    }

    public void flush() throws Exception {
        writeBatch(entries);
        entries.clear();
        currentSizeBytes = 0;
    }

    public abstract void writeBatch(List<T> entries) throws Exception;
}