package com.salpa.subject.domain.converter;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.salpa.common.core.domain.JsonData;
import com.salpa.subject.domain.data.DatabaseDocumentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class JsonConverter {

    @Autowired
    private ObjectMapper objectMapper;

    public List<String> fromJson(String data) {
        if (data == null) {
            return Collections.emptyList();
        } else {
            return Arrays.asList(data.split(","));
        }
    }

    public JSONObject toJson(List<String> array) {
        String json = objToJson(array);
        return JSONObject.parseObject(json);
    }

    public JSONObject toJson(DatabaseDocumentResponse response) {
        String json = objToJson(response);
        return JSONObject.parseObject(json);
    }

    public JSONObject toJson(JsonData<Object> data) {
        String json = objToJson(data);
        return JSONObject.parseObject(json);
    }

    public DatabaseDocumentResponse of(JSONObject json) {
        try {
            if (json == null) {
                return null;
            }
            return objectMapper.readValue(json.toString().getBytes(StandardCharsets.UTF_8), DatabaseDocumentResponse.class);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public JsonData toJsonData(JSONObject json) {
        try {
            if (json == null) {
                return null;
            }
            return objectMapper.readValue(json.toString().getBytes(StandardCharsets.UTF_8), JsonData.class);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public JSONObject objToJsonData(Object obj) {
        String json = objToJson(obj);
        return JSONObject.parseObject(json);
    }

    private String objToJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
