package com.wuban.tron.explore.handler;

import com.wuban.tron.explore.entity.Census;
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.CensusService;
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/24
 */
@Slf4j
public class CensusDataHandler extends AbstractJob implements ICensusDataHandler<Census> {

    private CensusService service;

    private PersistThreadPoolV2 threadPool;

    private final LinkedBlockingQueue<List<Census>> dataList;

    public CensusDataHandler() {
        this.dataList = new LinkedBlockingQueue<>();
        service = SpringContextUtil.getBean(CensusService.class);
        threadPool = PersistThreadPoolV2.getInstance();
    }

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

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

    @Override
    public void flush(List<Census> e) {
        if (!CollectionUtils.isEmpty(e)) {
            Census census = e.get(0);
            try {
                this.service.saveOrUpdateCensus(census);
                log.info("区块大小、交易数量统计 {}", census.toString());
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }


}
