package com.sheep.gamegroup.model.api;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.model.entity.BaseMessage;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import go.kfzssafe.Kfzssafe;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by realicing on 2018/4/2.
 */
public class BaseMessageConverter implements Converter<ResponseBody, BaseMessage> {

    @Override
    public BaseMessage convert(ResponseBody value) throws IOException {
        String string = value.string();
        String json = decrypt(string);
        BaseMessage baseMessage = JSONObject.parseObject(json, BaseMessage.class);
        return baseMessage;
    }


    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encrypt(String data) {
        return Kfzssafe.xEncodeS2S(data);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static String decrypt(String data) {
        if (TextUtils.isEmpty(data)) {
            Map<String, String> map = new HashMap<>();
            map.put("msg", "0-byte body");
            return JSON.toJSONString(map);
        }
        if (data.startsWith("{")) {
            return data;
        }
        try {
            return Kfzssafe.xDecodeS2S(data);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> map = new HashMap<>();
            map.put("msg", data);
            return JSON.toJSONString(map);
        }
    }
}
