package leigh.chain.etherium;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.VelocityWatch;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

public class ChainScannerApp {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ChainScannerApp.class);

    public static void main(String[] args) throws IOException {
        Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));

        VelocityWatch vw = new VelocityWatch(logger);

        // FIXME: Replace this with streaming filters - performance, utility.

        for (int i = 0; i < 34000; i++) {
            vw.event("block");
            // DefaultBlockParameterName.LATEST
            EthBlock ethBlock =
                    web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(BigInteger.valueOf(i)), false).send();
            List<EthBlock.TransactionResult> tran = ethBlock.getBlock().getTransactions();
            if (tran.size() > 0) {
                logger.info("Non-empty block: {}", ethBlock.getId());
                processBlock(tran);
            }
        }
    }

    public static void processBlock(List<EthBlock.TransactionResult> tran) {
        for (EthBlock.TransactionResult r : tran) {
            Object o = r.get();
            logger.info("--> txn {} {}", o, o.getClass());
        }
    }
}
