import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * This class contains the sample code to post a Wasabi action.
 */
public class Action {

  public static void main(String[] args) throws IOException {
    System.out.print(postAction("{{experiment.applicationName}}", "{{experiment.label}}", "UserName") ? "Action recorded" : "Action not recorded");
  }


  /**
   * This method calls the Wasabi Api to post an action for the specified experiment and user.
   *
   * @param application the ApplicationName the experiment is running in
   * @param experiment  the name of the Experiment
   * @param user        the user for whom the action should be posted
   * @return true if the action was recorded false otherwise
   * @throws IOException
   */
  private static boolean postAction(String application, String experiment, String user) throws IOException {

    String urlAction = String.format("{{baseUrl}}/events/applications/%s/experiments/%s/users/%s", application, experiment, user);

    URL url = new URL(urlAction);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("content-type", "application/json");
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    // the following could also be created with json frameworks
    writer.write("{\"events\":[{\"name\":\"ButtonClicked\", \"payload\":\"{\\\"state\\\":\\\"CA\\\"}\"}]}");
    writer.flush();

    // give it 500 milliseconds to respond
    connection.setReadTimeout(500);
    connection.connect();

    return connection.getResponseCode() == 201 ? true : false;
  }

}