package cn.com.qmth.stmms.biz.report.utils.unit;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class OptionCounter {

    public static final String BLANK_ANSWER = "#";

    public static int start = (int) 'A';

    private boolean multi;

    private Map<String, Integer> counter;

    public OptionCounter(boolean multi) {
        this.multi = multi;
        this.counter = new HashMap<String, Integer>();
    }

    public void process(String answer) {
        answer = formatAnswer(answer);
        int length = answer.length();
        if (multi) {
            // 支持多选题的选项拆分组合
            for (int i = 0; i < length; i++) {
                incr(String.valueOf(answer.charAt(i)));
            }
        } else {
            // 单一选项
            // 单选中选项个数为多个不计算
            if (answer.length() == 1) {
                incr(answer);
            }
        }
    }

    private void incr(String key) {
        Integer count = counter.get(key);
        if (count == null) {
            count = 0;
        }
        count++;
        counter.put(key, count);
    }

    /**
     * 对答案进行格式化，包括转换为大写，判断空选，去除非英文字母，排序等
     *
     * @param answer
     * @return
     */
    private String formatAnswer(String answer) {
        if (answer == null) {
            return BLANK_ANSWER;
        }
        int[] chars = new int[26];
        Arrays.fill(chars, 0);
        for (int i = 0; i < answer.length(); i++) {
            int index = (int) Character.toUpperCase(answer.charAt(i)) - start;
            Character.toUpperCase(answer.charAt(i));
            if (index >= 0 && index < 26) {
                chars[index] = 1;
            }
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 26; i++) {
            if (chars[i] == 1) {
                result.append((char) (start + i));
            }
        }
        if (result.length() == 0) {
            return BLANK_ANSWER;
        } else {
            return result.toString();
        }
    }

    public Map<String, Integer> getCounter() {
        return counter;
    }

    public boolean isMulti() {
        return multi;
    }

}
