package com.wuban.tron.explore.fetch;

import com.wuban.tron.explore.handler.AddressBalanceHandler;
import com.wuban.tron.explore.handler.IAddressBalanceHandler;
import com.wuban.tron.explore.constant.Constant;
import com.wuban.tron.explore.domain.TronAccount;
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/11/12
 */
@Slf4j
public class AddressBalanceFetcher<T> extends AbstractJob implements IAddressBalanceFetcher {

    private TronService tronService;

    private IAddressBalanceHandler handler;

    private StringRedisTemplate stringRedisTemplate;

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

    @Override
    public List fetch() {
        List<TronAccount> dataList = new ArrayList<>();
        Long num = 0L;

        try {
            // Redis 获取账户地址
            String address = this.stringRedisTemplate.opsForSet().pop(Constant.ADDRESS_KEY);
            if (!StringUtils.isEmpty(address)) {
                TronAccount data = tronService.getAccount(address);
                if (data != null && data.getBalance() != null) {
                    dataList.add(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<TronAccount> list = fetch();
            if (CollectionUtils.isEmpty(list)) {
                return false;
            }
            send(list);
            return true;
        } catch (final Exception e) {
            log.error("fetch exception", e);
            return false;
        }
    }
}
