package com.vshaldin.core.loader;

import com.vshaldin.core.datepipe.DataPipe;
import com.vshaldin.core.domain.entity.ConnectionEntity;
import com.vshaldin.core.domain.service.ConnectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

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

/**
 * DBLoader
 */
@Component
@Scope("prototype")
public class DBLoader implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(DBLoader.class);

    public static final int BATCH_SIZE = 50;

    private final DataPipe<ConnectionEntity> pipe;
    private final ConnectionService service;
    private final List<ConnectionEntity> batchEntities;

    /**
     * Constructor
     *
     * @param pipe    {@link DataPipe} pipe
     * @param service {@link ConnectionService} connection service
     */
    @Autowired
    public DBLoader(DataPipe<ConnectionEntity> pipe, ConnectionService service) {
        this.pipe = pipe;
        this.service = service;
        batchEntities = new ArrayList<>();
    }

    @Override
    public void run() {

        while (pipe.size() > 0 || pipe.isOpened()) {
            ConnectionEntity entry = pipe.poll();
            if (entry != null)
                persistEntry(entry);
        }
        if (batchEntities.size() > 0) {
            try {
                service.saveAll(batchEntities);
            } catch (Exception ex) {
                logger.error("Can't persist entities", ex);
            }
        }
    }

    /**
     * Persists entity to DB
     */
    private void persistEntry(final ConnectionEntity entity) {
        if (entity != null) {
            batchEntities.add(entity);
            if (batchEntities.size() > 0 && batchEntities.size() % BATCH_SIZE == 0) {
                try {
                    service.saveAll(batchEntities);
                } catch (Exception ex) {
                    logger.error("Can't persist entities", ex);
                }
                batchEntities.clear();
            }
        } else
            logger.error("Can't persist null log entity");
    }
}
