package com.wuban.tron.explore.fetch;

import com.wuban.tron.explore.constant.Constant;
import com.wuban.tron.explore.domain.TronTransEvent;
import com.wuban.tron.explore.handler.AddressBalanceHandler;
import com.wuban.tron.explore.handler.ContractEventHandler;
import com.wuban.tron.explore.handler.IAddressBalanceHandler;
import com.wuban.tron.explore.handler.IContractEventHandler;
import com.wuban.tron.explore.service.TronService;
import com.wuban.tron.explore.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 *  <core>合约事件抓取者服务接口方法实现类</core>
 *
 * @author sky
 * @date 2020/12/4
 */
@Slf4j
public class ContractEventFetcher<T> extends AbstractJob implements IContractEventFetcher {

    private TronService tronService;

    private IContractEventHandler handler;

    private StringRedisTemplate stringRedisTemplate;

    ContractEventFetcher(final ContractEventHandler handler) {
        this.handler = handler;
        tronService = SpringContextUtil.getBean(TronService.class);
        stringRedisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
    }

    @Override
    public List fetch() {
        List<TronTransEvent> dataList = new ArrayList<>();

        try {
            // Redis 获取合约地址
            String address = this.stringRedisTemplate.opsForSet().pop(Constant.CONTRACT_ADDRESS_KEY);
            if (!StringUtils.isEmpty(address)) {
                List<TronTransEvent> data = tronService.getContractEvent(address);
                if (data != null) {
                    dataList.addAll(data);
                }
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }

        return dataList;
    }

    @Override
    public void send(List list) throws InterruptedException {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        this.handler.receive(list);
    }

    @Override
    public boolean execute() {
        try {
            final List<TronTransEvent> list = fetch();
            if (CollectionUtils.isEmpty(list)) {
                return false;
            }
            send(list);
            return true;
        } catch (final Exception e) {
            log.error("fetch exception", e);
            return false;
        }
    }
}
