package com.chain.api;

import com.chain.exception.ChainException;
import com.chain.http.Context;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ControlProgram {
  @SerializedName("control_program")
  public String program;

  public static String retireProgram() {
    return "6a";
  }

  public static class Builder {
    public String type;
    public Map<String, Object> parameters;

    public Builder() {
      this.parameters = new HashMap<>();
    }

    public ControlProgram create(Context ctx) throws ChainException {
      List<ControlProgram> programs = ControlProgram.Builder.create(ctx, Arrays.asList(this));
      return programs.get(0);
    }

    public static List<ControlProgram> create(Context ctx, List<Builder> programs)
        throws ChainException {
      Type type = new TypeToken<List<ControlProgram>>() {}.getType();
      return ctx.request("create-control-program", programs, type);
    }

    public Builder controlWithAccountById(String accountId) {
      this.type = "account";
      this.addParameter("account_id", accountId);
      return this;
    }

    public Builder controlWithAccountByAlias(String accountAlias) {
      this.type = "account";
      this.addParameter("account_alias", accountAlias);
      return this;
    }

    public Builder setType(String type) {
      this.type = type;
      return this;
    }

    public Builder addParameter(String key, Object value) {
      this.parameters.put(key, value);
      return this;
    }

    public Builder setParameters(Map<String, Object> parameters) {
      this.parameters = parameters;
      return this;
    }
  }
}

@@ -17,16 +17,57 @@
 n.api;%0A%0A
+import com.chain.exception.APIException;%0A
 import c
@@ -93,32 +93,32 @@
 ChainException;%0A
-
 import com.chain
@@ -447,16 +447,104 @@
 ogram;%0A%0A
+  // Error data%0A  public String code;%0A  public String message;%0A  public String detail;%0A%0A
   public
@@ -944,30 +944,222 @@
     
-return programs.get(0)
+ControlProgram result = programs.get(0);%0A      if (result.program == null %7C%7C result.program.isEmpty()) %7B%0A        throw new APIException(result.code, result.message, result.detail, null);%0A      %7D%0A      return result
 ;%0A  

throw exception for bad `ControlProgram#create` call