package leigh.chain.directory;

import leigh.chain.BlockScanner;
import leigh.chain.BlockTranHandler;
import leigh.chain.ReplayOption;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.util.UniversalJob;
import org.bouncycastle.util.encoders.Hex;
import org.web3j.protocol.core.methods.response.EthBlock;

/**
 * This daemon implements the LeighChain directory service.
 *
 * @author Alex Leigh
 */
public class DirectoryDaemon {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(DirectoryDaemon.class);

    public static void main(String[] args) {
        UniversalJob.banner(logger, "DirectoryDaemon");

        DirectoryStateMachine dsm = new DirectoryStateMachine(new RamDirectoryStore());

        if (args.length != 1) {
            System.err.println("Usage: DirectoryDaemon url");
            System.err.println("Example: DirectoryDaemon http://localhost:8545");
            System.exit(UniversalJob.RET_BADARGS);
        }

        BlockScanner scanner = new BlockScanner(args[0], ReplayOption.PAST, new BlockTranHandler() {
            @Override
            public void event(EthBlock.Block block, EthBlock.TransactionObject txn) {
                logger.info("TXN [to: {}] [value: {}]", txn.getTo(), txn.getValue());

                String v = txn.getInput();
                logger.info("Raw input: {}", v);
                if (v.startsWith("0x")) v = v.substring(2);

                byte[] d = Hex.decode(v);
                logger.info("Decoded input: {}", new String(d));
            }
        });
        scanner.scan();
        logger.info("Scan finished.");

        // This is required because the block filter never seems to really exit.
        System.exit(UniversalJob.RET_OK);
    }
}
