package com.ttstd.dialer.manager;

import android.content.Context;
import android.util.Log;

import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.ttstd.dialer.bean.CityInfo;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class CsvDeserializer {
    private static final String TAG = "CsvDeserializer";

    /**
     * 从assets文件夹中的CSV文件反序列化为对象列表
     *
     * @param context  上下文
     * @param fileName assets中的CSV文件名
     * @return 对象列表
     */
    public static List<CityInfo> deserializeFromAssets(Context context, String fileName) {
        InputStream inputStream = null;
        Reader reader = null;
        try {
            long time = System.currentTimeMillis();
            // 从assets获取CSV文件输入流
            inputStream = context.getAssets().open(fileName);
            reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);

            // 创建映射策略，使用CSV头部列名映射到对象字段
            HeaderColumnNameMappingStrategy<CityInfo> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(CityInfo.class);

            // 创建CsvToBean并进行转换
            CsvToBean<CityInfo> csvToBean = new CsvToBeanBuilder<CityInfo>(reader)
                    .withMappingStrategy(strategy)
                    .withIgnoreLeadingWhiteSpace(true)
                    .withIgnoreEmptyLine(true) // 忽略空行
                    .withThrowExceptions(false) // 不抛出异常，便于调试
                    .build();
            Log.e(TAG, "deserializeFromAssets: finish " + (System.currentTimeMillis() - time) + "ms");
            // 转换并返回结果列表
            return csvToBean.parse();
        } catch (IOException e) {
            Log.e(TAG, "Error reading CSV file: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "Error during CSV deserialization: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 确保关闭流，避免资源泄漏
            try {
                if (reader != null) {
                    reader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "Failed to close stream: " + e.getMessage());
            }
        }
        return new ArrayList<>();
    }


    /**
     * 从输入流反序列化为对象列表
     *
     * @param inputStream CSV文件输入流
     * @return 对象列表
     */
    public static List<CityInfo> deserializeFromStream(InputStream inputStream) {
        try {
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);

            HeaderColumnNameMappingStrategy<CityInfo> strategy = new HeaderColumnNameMappingStrategy<>();
            strategy.setType(CityInfo.class);

            CsvToBean<CityInfo> csvToBean = new CsvToBeanBuilder<CityInfo>(reader)
                    .withMappingStrategy(strategy)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            return csvToBean.parse();

        } catch (Exception e) {
            Log.e(TAG, "Error during CSV deserialization: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }
}
