/*
 * Copyright (c) 2012, Apptentive, Inc. All Rights Reserved.
 * Please refer to the LICENSE file for the terms and conditions
 * under which redistribution and use of this file is permitted.
 */

package com.apptentive.android.sdk.offline;

import com.apptentive.android.sdk.Log;
import com.apptentive.android.sdk.module.survey.Question;
import com.apptentive.android.sdk.module.survey.SurveyDefinition;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @author Sky Kelsey
 */
public class SurveyPayload extends Payload {

	private SurveyDefinition definition;

	public SurveyPayload(SurveyDefinition definition) {
		super();
		this.definition = definition;
	}

	/**
	 * Return Object with array of Objects that are themselves a single key/value pair.
	 *
	 * @return JSON String
	 */
	@Override
	public String getAsJSON() {
		try {
			JSONObject record = new JSONObject();
			JSONObject survey = new JSONObject();
			survey.put("id", definition.getId());

			JSONObject answers = new JSONObject();
			List<Question> questions = this.definition.getQuestions();
			for(Question question : questions) {
				String id = question.getId();
				String[] questionAnswers = question.getAnswers();
				if(questionAnswers.length == 1 && !questionAnswers[0].equals("")) {
					answers.put(id, questionAnswers[0]);
				} else {
					JSONArray jsonArray = new JSONArray();
					for (String answer : questionAnswers) {
						jsonArray.put(answer);
					}
					answers.put(id, jsonArray);
				}
			}
			survey.put("responses", answers);
			record.put("survey", survey);
			root.put("record", record);
			return super.getAsJSON();
		} catch (JSONException e) {
			Log.e("Error encoding survey JSON.", e);
		}
		return null;
	}

}

@@ -1287,25 +1287,23 @@
 gth 
-== 1 && !
+%3E 1 %7C%7C 
 question
 Answ
@@ -1302,85 +1302,117 @@
 tion
-Answers%5B0%5D.equals(%22%22)) %7B%0A%09%09%09%09%09answers.put(id, questionAnswers%5B0%5D);%0A%09%09%09%09%7D else
+.getType() == Question.QUESTION_TYPE_MULTICHOICE %7C%7C question.getType() == Question.QUESTION_TYPE_MULTISELECT)
  %7B%0A%09
@@ -1568,16 +1568,137 @@
 Array);%0A
+%09%09%09%09%7D else if(questionAnswers.length == 1 && !questionAnswers%5B0%5D.equals(%22%22)) %7B%0A%09%09%09%09%09answers.put(id, questionAnswers%5B0%5D);%0A
 %09%09%09%09%7D%0A%09%09

Fix multiselect responses to always wrap in an array. [#ANDROID-70]