package com.aps.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.DeserializationFeature;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Scanner;

public class JsonFileReader {
    
    public static <T> List<T> readListFromResources(String fileName, Class<T> clazz) throws IOException {
        // 1. 从classpath读取文件
        try (InputStream inputStream = JsonFileReader.class.getClassLoader().getResourceAsStream(fileName)) {
            if (inputStream == null) {
                throw new IOException("File not found in resources: " + fileName);
            }
            
            // 使用Scanner替代readAllBytes以兼容Java 8
            Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name()).useDelimiter("\\A");
            String jsonContent = scanner.hasNext() ? scanner.next() : "";
            
            // 2. 配置ObjectMapper支持Java 8时间API
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.registerModule(new JavaTimeModule());
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            // 添加更多配置确保字段正确映射
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
            
            // 3. 反序列化JSON到对象列表
            return objectMapper.readValue(jsonContent,
                objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        }
    }


    public static <T> List<T> readListFromFile(String filePath, Class<T> clazz) throws IOException {
        // 1. 检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            throw new IOException("File not found: " + filePath);
        }

        // 2. 读取文件内容
        Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name()).useDelimiter("\\A");
        String jsonContent = scanner.hasNext() ? scanner.next() : "";

        // 3. 配置ObjectMapper支持Java 8时间API
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 添加更多配置确保字段正确映射
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

        // 4. 反序列化JSON到对象列表
        return objectMapper.readValue(jsonContent,
                objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
    }
}