package chaincode.example;

import java.util.List;
import org.hyperledger.fabric.shim.*;

public class SimpleChaincode extends ChaincodeBase {

    @Override
    public Response init(ChaincodeStub stub) {
        try {
            System.out.println("Init java simple chaincode");
            return new Response(Response.Status.SUCCESS, "init success", null);
        } catch (Throwable e) {
            return new Response(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), null);
        }
    }

    @Override
    public Response invoke(ChaincodeStub stub) {
        try {
            System.out.println("Invoke java simple chaincode");
            String func = stub.getFunction();
            List<String> params = stub.getParameters();
            if (func.equals("set")) {
                return set(stub, params);
            }
            if (func.equals("get")) {
                return get(stub, params);
            }

            return new Response(Response.Status.INTERNAL_SERVER_ERROR, "Invalid invoke function name. Expecting one of: [\"set\", \"get\"]", null);
        } catch (Throwable e) {
            return new Response(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), null);
        }
    }

    private Response set(ChaincodeStub stub, List<String> args) {
        if (args.size() != 2) {
            return new Response(Response.Status.INTERNAL_SERVER_ERROR, "Incorrect number of arguments. Expecting 2", null);
        }
        String key = args.get(0);
        String value = args.get(1);

        System.out.println(String.format("Set key: %s, value: %s", key, value));

        stub.putStringState(key, value);

        System.out.println("Transfer complete");
        return new Response(Response.Status.SUCCESS, "invoke finished successfully", null);
    }

    private Response get(ChaincodeStub stub, List<String> args) {
        if (args.size() != 1) {
            return new Response(Response.Status.INTERNAL_SERVER_ERROR, "Incorrect number of arguments. Expecting 1", null);
        }
        String key = args.get(0);
        String val = stub.getStringState(key);
        if (val == null) {
            return new Response(Response.Status.INTERNAL_SERVER_ERROR, String.format("Error: state for %s is null", key), null);
        }
        System.out.println(String.format("Query key: %s, value: %s\n", key, val));
        return new Response(Response.Status.SUCCESS, val, val.getBytes());
    }

    public static void main(String[] args) {
        new SimpleChaincode().start(args);
    }
}
