package com.wuban.tron.explore.handler;

import com.wuban.tron.explore.domain.TronResponseData;
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.TransactionService;
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/11/04
 */
@Slf4j
public class BlockDataHandler extends AbstractJob implements IBlockDataHandler {

    private TransactionService transactionService;

    private PersistThreadPoolV2 threadPool;

    private final LinkedBlockingQueue<List<TronResponseData>> dataList;

    public BlockDataHandler() {
        this.dataList = new LinkedBlockingQueue<>();
        transactionService = SpringContextUtil.getBean(TransactionService.class);
        threadPool = PersistThreadPoolV2.getInstance();
    }

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

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

    @Override
    public void flush(List list) {
        if (!CollectionUtils.isEmpty(list)) {
            try {
                this.transactionService.save(list);
            } catch (Exception e) {
                log.info("同步到DB失败 param:{}", list.toString());
            }
        }

    }


}
