package cn.com.qmth.stmms.admin.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.google.common.io.ByteStreams;

public class StudentJsonUtils {

    public static final String ANSWER_SPLIT = ",";

    public static final String[] answerArray = new String[] { "#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
            "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    public static String toAnswers(String text) {
        List<String> list = new ArrayList<>();
        JSONArray array = JSONArray.fromObject(text);
        for (int i = 0; i < array.size(); i++) {
            JSONObject answerJson = array.getJSONObject(i);
            Object answerObject = answerJson.get("answer");
            String answer = "";
            if (answerObject instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) answerObject;
                if (jsonArray.size() == 0) {
                    answer = "#";
                }
                for (int l = 0; l < jsonArray.size(); l++) {
                    Object o = jsonArray.get(l);
                    if (o instanceof Integer) {
                        int index = jsonArray.getInt(l);
                        answer = answer + answerArray[index];
                    }
                }
            } else if (answerObject instanceof Boolean) {
                answer = answerJson.getBoolean("answer") ? "A" : "B";
            } else if (answerObject instanceof JSONObject) {
                if (((JSONObject) answerObject).isNullObject()) {
                    answer = "#";
                }
            }
            if (StringUtils.isNotBlank(answer)) {
                list.add(answer);
            }
        }
        return StringUtils.join(list, ANSWER_SPLIT);
    }

    public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException {
        File file = new File("/Users/ting.yin/Downloads/10128279.json");
        String text = new String(ByteStreams.toByteArray(new FileInputStream(file)), "UTF-8");
        String s = toAnswers(text);
        System.out.println(s);
    }
}
