package com.bytesw.bytebot.etl.batch.writer;

import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import com.bytesw.bytebot.etl.beans.EventBean;
import com.bytesw.bytebot.etl.beans.ProcessMessageResult;
import com.bytesw.bytebot.etl.services.ProcessMessageService;
import com.bytesw.xdf.multitenant.core.ThreadLocalStorage;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;

import javax.transaction.Transactional;
import java.util.List;

@Log4j2
public class ByteBotJPAWriter implements ItemWriter<DynaBean>, StepExecutionListener {

    @Getter
    @Setter
    private ProcessMessageService service;

    @Override
    @Transactional
    public void write(List<? extends DynaBean> list) throws Exception {
        for (DynaBean dynaBean : list) {
            EventBean eventBean = (EventBean) dynaBean.get("bean");
            String json = (String) dynaBean.get("data");
            ProcessMessageResult result = service.processMessage(json, eventBean.getSenderId());
            log.debug(String.format("senderId: %s, processed: %s", eventBean.getSenderId(), result.isProcessed()));
            service.saveHistory(eventBean.getId(), eventBean.getSenderId());
        }
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        String tenantId = stepExecution.getJobParameters().getString("tenantId");
        ThreadLocalStorage.setTenantName(tenantId);
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        return stepExecution.getExitStatus();
    }
}
