package leigh.chain.blocktail;

import io.reactivex.Flowable;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.StringAccumulatorV2;
import leigh.mecha.util.UniversalJob;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.http.HttpService;

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

    public static void main(String[] args) {
        if (args.length != 3) {
            System.err.println("Usage: BlockTail url replay continuous");
            System.err.println("Example: BlockTail http://localhost:8545 false true");
            System.exit(UniversalJob.RET_BADARGS);
        }

        Web3j web3j = Web3j.build(new HttpService(args[0]));

        boolean replay = Boolean.parseBoolean(args[1]);
        boolean continuous = Boolean.parseBoolean(args[2]);

        Flowable<EthBlock> subscription;
        if (replay) {
            if (continuous) {
                subscription = web3j.replayPastAndFutureBlocksFlowable(DefaultBlockParameterName.EARLIEST, true);
            } else {
                subscription = web3j.replayPastBlocksFlowable(DefaultBlockParameterName.EARLIEST, true);
            }
        } else {
            subscription = web3j.blockFlowable(true);
        }

        System.out.println("BLOCK_ID,TIMESTAMP,MINER,SIZE");

        // Weird case.
        if (!replay && !continuous) System.exit(UniversalJob.RET_OK);

        subscription.blockingForEach(ethBlock -> {
            EthBlock.Block b = ethBlock.getBlock();

            StringAccumulatorV2 sa = new StringAccumulatorV2(",");
            sa.push(String.valueOf(b.getNumber()));
            sa.push(String.valueOf(b.getTimestamp()));
            sa.push(b.getMiner());
            sa.push(b.getSize().toString());

            System.out.println(sa.asString());
        });

        System.exit(UniversalJob.RET_OK);
    }
}
