package com.wuban.tron.explore.handler;

import com.wuban.tron.explore.domain.TronTransEvent;
import com.wuban.tron.explore.fetch.AbstractJob;
import com.wuban.tron.explore.fetch.PersistThreadPool;
import com.wuban.tron.explore.fetch.PersistThreadPoolV2;
import com.wuban.tron.explore.service.ContractEventService;
import com.wuban.tron.explore.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 *  <core>合约事件处理者服务接口方法实现类</core>
 *
 * @author sky
 * @date 2020/12/4
 */
@Slf4j
public class ContractEventHandler extends AbstractJob implements IContractEventHandler<TronTransEvent> {

    private ContractEventService contractEventService;

    private PersistThreadPoolV2 threadPool;

    private final LinkedBlockingQueue<List<TronTransEvent>> dataList;

    public ContractEventHandler() {
        this.dataList = new LinkedBlockingQueue<>();
        contractEventService = SpringContextUtil.getBean(ContractEventService.class);
        threadPool = PersistThreadPoolV2.getInstance();
    }

    @Override
    public boolean execute() {
        final List<TronTransEvent> list = this.dataList.poll();
        if(list != null && list.size() != 0) {
            threadPool.getPool().execute(() -> flush(list));
        }
        return true;
    }

    @Override
    public void receive(List<TronTransEvent> e) throws InterruptedException {
        if (!CollectionUtils.isEmpty(e)) {
            this.dataList.put(e);
        }
    }

    @Override
    public void flush(List<TronTransEvent> e) {
        if (!CollectionUtils.isEmpty(e)) {
            this.contractEventService.batchInsert(e);
        }
    }


}
