package com.jasonkliu.qualtricsapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

import org.json.JSONArray;
import org.json.JSONObject;

public class MainActivity extends Activity {

    private boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return (netInfo != null && netInfo.isConnectedOrConnecting());
    }

    TextView display;
    Button linksurvey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        display = (TextView) findViewById(R.id.tvDisplay);
        linksurvey = (Button) findViewById(R.id.bLinkSurvey);

        Uri.Builder builder = new Uri.Builder();
        builder.scheme("https")
            .authority("survey.qualtrics.com")
            .appendPath("WRAPI")
            .appendPath("ControlPanel")
            .appendPath("api.php")
            .appendQueryParameter("API_SELECT", "ControlPanel")
            .appendQueryParameter("Version", "2.4")
            .appendQueryParameter("Request", "getSurveys")
            .appendQueryParameter("Format", "JSON")
            .appendQueryParameter("JSONPrettyPrint", "1");
        String myUrl = builder.build().toString();
        Log.d("myURL", myUrl);

        // If you want to use XML Parameters instead, use the lines:
        // .appendQueryParameter("User", "user#group")
        // .appendQueryParameter("Token", "token")

        JsonObject json = new JsonObject();
        json.addProperty("User", new DeveloperKey().USER_ID);
        json.addProperty("Token", new DeveloperKey().DEVELOPER_KEY);

        if (isOnline()) {
            Ion.with(this)
                .load(myUrl)
                .setJsonObjectBody(json)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        // do stuff with the result or error
                        if (result != null) {
                            Log.d("JSONresult", result.toString());

                            /* Ion uses the Gson Library, which makes pretty printing hard (it's
                             * normally json.toString(4) in org.json libraries.
                             *
                             * Below is a one-liner of the following:
                             * Gson gs = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
                             * JsonParser parser = new JsonParser();
                             * JsonElement je = parser.parse(result.toString());
                             * display.setText(gs.toJson(je));
                             *
                             * https://stackoverflow.com/questions/4105795
                             * https://stackoverflow.com/questions/11020894
                             */

                            display.setText(new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
                                    .toJson(new JsonParser().parse(result.toString())));

                            /* Result is of type:
                             * {
                             *    "Meta": {
                             *        "Status": "Success",
                             *        "Debug": ""
                             *    },
                             *    "Result": {
                             *        "Surveys": [
                             *            {
                             *                "responses": "1",
                             *                "SurveyType": "SV",
                             *                "SurveyID": "SV_eidnumber",
                             *                "SurveyName": "SurveyName",
                             *                "SurveyDescription": "SurveyDescritption",
                             *                "SurveyOwnerID": "UR_aidnumber",
                             *                "SurveyStatus": "Active",
                             *                "SurveyStartDate": "0000-00-00 00:00:00",
                             *                "SurveyExpirationDate": "0000-00-00 00:00:00",
                             *                "SurveyCreationDate": "2015-03-19 12:06:13",
                             *                "CreatorID": "UR_aidnumber",
                             *                "LastModified": "2015-03-19 12:07:06",
                             *                "LastActivated": "2015-03-19 12:07:06",
                             *                "UserFirstName": "User",
                             *                "UserLastName": "Name"
                             *            }
                             *            {
                             *                ...
                             *            }
                             *        ]
                             *    }
                             *}
                             */

                            JsonArray ja = result.getAsJsonObject("Result").getAsJsonArray("Surveys");

                            for (final JsonElement type : ja) {
                                final JsonObject coords = type.getAsJsonObject();
                                Log.d("new", coords.getAsJsonObject().getAsJsonPrimitive("SurveyID").toString());
                            }
                            /*for (int i = 0; i < ja.size(); i++) {
                                JsonElement inter = ja.get(i).getAsJsonObject();
                                String test = inter.getAsJsonObject("SurveyID");
                                Log.d("ja" + Integer.toString(i), ja.get(i).getAsJsonObject("SurveyID").toString());
                            }*/
                            Log.d("JSONObject", result.getAsJsonObject("Result").getAsJsonArray("Surveys").toString());
                            linksurvey.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //Uri uriUrl1 = Uri.parse(addrlist[newindex]);
                                    //Intent launchBrowser1 = new Intent(Intent.ACTION_VIEW, uriUrl1);
                                    //startActivity(launchBrowser1);
                                }
                            });
                        } else {
                            Log.d("JSONexcept", e.toString());
                        }
                    }
                });
        }
    }

}

@@ -1038,16 +1038,46 @@
 ksurvey;
+%0A    String lastsurveyid = %22%22;
 %0A%0A    @O
@@ -5852,16 +5852,82 @@
 veys%22);%0A
+                            Log.d(%22JSONObject%22, ja.toString());%0A%0A%0A
 %0A       
@@ -5970,20 +5970,22 @@
 Element 
-type
+survey
  : ja) %7B
@@ -6038,21 +6038,21 @@
 ect 
-coords = type
+each = survey
 .get
@@ -6103,27 +6103,27 @@
     
-Log.d(%22new%22, coords
+lastsurveyid = each
 .get
@@ -6182,539 +6182,146 @@
 ng()
-);%0A                            %7D%0A                            /*for (int i = 0; i %3C ja.size(); i++) %7B%0A                                JsonElement inter = ja.get(i).getAsJsonObject();%0A                                String test = inter.getAsJsonObject(%22SurveyID%22);%0A                                Log.d(%22ja%22 + Integer.toString(i), ja.get(i).getAsJsonObject(%22SurveyID%22).toString());%0A                            %7D*/%0A                            Log.d(%22JSONObject%22, result.getAsJsonObject(%22Result%22).getAsJsonArray(%22Surveys%22).toString());
+.replaceAll(%22%5C%22%22, %22%22);  // remove double quotes%0A                                Log.d(%22new%22, lastsurveyid);%0A                            %7D%0A
 %0A   
@@ -6544,18 +6544,16 @@
         
-//
 Uri uriU
@@ -6572,26 +6572,66 @@
 rse(
-addrlist%5Bnewindex%5D
+%22https://yalesurvey.qualtrics.com/SE/?SID=%22 + lastsurveyid
 );%0A 
@@ -6665,18 +6665,16 @@
         
-//
 Intent l
@@ -6766,18 +6766,16 @@
         
-//
 startAct

Add clickable button for survey