package ru.yandex.webmaster3.core.logbroker.writer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import lombok.extern.slf4j.Slf4j;

import ru.yandex.kikimr.persqueue.producer.AsyncProducer;
import ru.yandex.kikimr.persqueue.producer.transport.message.inbound.ProducerInitResponse;
import ru.yandex.kikimr.persqueue.producer.transport.message.inbound.ProducerWriteResponse;

/**
 * ishalaru
 * 10.06.2021
 **/
@Slf4j
public class LogbrokerClientWriter {
    private final AsyncProducer producer;
    private final ProducerInitResponse sessionInfo;
    private boolean isValid;

    public LogbrokerClientWriter(AsyncProducer producer, ProducerInitResponse sessionInfo) {
        this.producer = producer;
        this.sessionInfo = sessionInfo;
        this.isValid = true;
    }

    public void sessionIsBroken() {
        isValid = false;
    }

    public boolean IsValid() {
        return isValid;
    }

    public CompletableFuture<ProducerWriteResponse> writeData(byte[] data) {
        return producer.write(data);
    }

    public List<CompletableFuture<ProducerWriteResponse>> writeData(List<byte[]> data) {
        List<CompletableFuture<ProducerWriteResponse>> result = new ArrayList<>();
        for (byte[] item : data) {
            result.add(producer.write(item));
        }
        return result;
    }

    public void close() {
        log.info("Producer closed topic: {}, partitionNumber: {}, sessionId: {}", sessionInfo.getTopic(), sessionInfo.getPartition(),sessionInfo.getSessionId());
        isValid = false;
        producer.close();
    }
}
