package com.njcn.gather.pqdif.service.support;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.pqdif.pojo.enums.PqdifResponseEnum;
import com.njcn.gather.pqdif.pojo.param.PqPqdifPathParam;

import java.util.ArrayList;
import java.util.List;

public final class PqdifImportParser {

    private PqdifImportParser() {
    }

    public static List<PqPqdifPathParam.ImportItem> parse(String content) {
        try {
            JSONArray jsonArray = JSON.parseArray(content);
            if (jsonArray == null) {
                throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
            }
            List<PqPqdifPathParam.ImportItem> items = new ArrayList<>();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject == null) {
                    throw new BusinessException(PqdifResponseEnum.IMPORT_ITEM_NOT_NULL);
                }
                PqPqdifPathParam.ImportItem item = jsonObject.toJavaObject(PqPqdifPathParam.ImportItem.class);
                Object msg = jsonObject.get("msg");
                item.setMsg(normalizeMsg(msg));
                items.add(item);
            }
            return items;
        } catch (BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new BusinessException(PqdifResponseEnum.JSON_FORMAT_ERROR);
        }
    }

    private static String normalizeMsg(Object msg) {
        if (msg == null) {
            return null;
        }
        if (msg instanceof String) {
            return (String) msg;
        }
        return JSON.toJSONString(msg);
    }
}
