package com.hcl.bigchaindbDriver;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Test;

import java.awt.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Unit tests for {@link BigchainDB}.
 *
 * Created by mark.grand on 1/12/2017.
 */
public class BigchainDBTest {
    private final static String HOST_ADDRESS = "example.com";
    private final static int PORT_NUMBER = 34567;
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void createInstance() throws Exception {
        final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER);
        assertEquals(HOST_ADDRESS, bigchainDB.getHostAddress());
        assertEquals(PORT_NUMBER, bigchainDB.getPort());
        assertNotNull(bigchainDB.getObjectMapper());
    }

    @Test
    public void createInstance1() throws Exception {
        final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER, objectMapper);
        assertEquals(HOST_ADDRESS, bigchainDB.getHostAddress());
        assertEquals(PORT_NUMBER, bigchainDB.getPort());
        assertEquals(objectMapper, bigchainDB.getObjectMapper());
    }

    @Test
    public void createAssetTransaction() throws Throwable {
        final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER);
        final UnsignedCreateTransaction transaction = bigchainDB.createAssetTransaction(new Point(1, 0));
        assertNotNull(transaction);

        final JsonNode json = getAssetData(transaction);
        assertEquals(1, json.get("x").asInt());
        assertEquals(0, json.get("y").asInt());
    }

    private JsonNode getAssetData(UnsignedCreateTransaction transaction) {
        //noinspection RedundantTypeArguments
        return transaction.getAssetData().<RuntimeException>orElseThrow(() -> {throw new RuntimeException();});
    }

    @Test
    public void createAssetTransaction1() throws Exception {
        final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER);
        final ObjectNode json = objectMapper.createObjectNode();
        json.set("foo", JsonNodeFactory.instance.textNode("bar"));
        final UnsignedCreateTransaction transaction = bigchainDB.createAssetTransaction(json);
        assertNotNull(transaction);
        assertEquals(json, getAssetData(transaction));
    }

    @Test
    public void transferAssetTransaction() throws Exception {
        final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER);
        final UnsignedTransferTransaction transaction = bigchainDB.transferAssetTransaction();
        assertNotNull(transaction);
        //assertEquals(ASSET_ID, transaction.getAssetId());
    }

}