package com.njcn.advance.event.cause.io;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * COMTRADE格式数据文件读取器
 * 对应C语言中的comtrade_read函数
 */
public class ComtradeReader {
    private static final Logger logger = LoggerFactory.getLogger(ComtradeReader.class);
    
    /**
     * COMTRADE数据读取结果
     */
    public static class ComtradeData {
        private float[] ua;
        private float[] ub; 
        private float[] uc;
        private int sampleCount;
        private int sampleRate;
        
        public ComtradeData(float[] ua, float[] ub, float[] uc, int sampleCount, int sampleRate) {
            this.ua = ua;
            this.ub = ub;
            this.uc = uc;
            this.sampleCount = sampleCount;
            this.sampleRate = sampleRate;
        }
        
        public float[] getUa() { return ua; }
        public float[] getUb() { return ub; }
        public float[] getUc() { return uc; }
        public int getSampleCount() { return sampleCount; }
        public int getSampleRate() { return sampleRate; }
    }
    
    /**
     * 读取COMTRADE格式的DAT文件
     * @param filename 文件名
     * @param xsa A相比例因子
     * @param xsb B相比例因子
     * @param xsc C相比例因子
     * @param inputSampleRate 输入采样率
     * @param outputSampleRate 输出采样率
     * @param maxSamples 最大采样点数
     * @param recordSize 每个记录的字节数（20或14）
     * @return COMTRADE数据对象
     * @throws IOException 文件读取异常
     */
    public static ComtradeData readComtradeFile(String filename, 
                                              float xsa, float xsb, float xsc,
                                              int inputSampleRate, int outputSampleRate, 
                                              int maxSamples, int recordSize) throws IOException {
        
        logger.info("开始读取COMTRADE文件: {}", filename);
        logger.info("参数: xsa={}, xsb={}, xsc={}, 输入采样率={}, 输出采样率={}, 记录大小={}字节", 
                   xsa, xsb, xsc, inputSampleRate, outputSampleRate, recordSize);
        
        File file = new File(filename);
        if (!file.exists()) {
            throw new IOException("文件不存在: " + filename);
        }
        
        long fileSize = file.length();
        int recordCount = (int)(fileSize / recordSize);
        
        logger.info("文件大小: {} 字节, 记录数: {}", fileSize, recordCount);
        
        // 读取文件数据
        byte[] buffer = new byte[(int)fileSize];
        try (FileInputStream fis = new FileInputStream(file)) {
            int bytesRead = fis.read(buffer);
            if (bytesRead != fileSize) {
                throw new IOException("文件读取不完整");
            }
        }
        
        // 解析数据
        float[] ua = new float[maxSamples];
        float[] ub = new float[maxSamples];
        float[] uc = new float[maxSamples];
        
        int dataCount = 0;
        int decimationMod = inputSampleRate / outputSampleRate;
        
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);  // 小端字节序
        
        for (int i = 0; i < recordCount && dataCount < maxSamples; i++) {
            // 根据采样率转换决定是否处理此记录
            if (inputSampleRate == outputSampleRate || (i % decimationMod) == 0) {
                
                int baseOffset = i * recordSize;
                
                // 读取三相电压数据（从第8字节开始，每相2字节）
                short dataA = byteBuffer.getShort(baseOffset + 8);
                short dataB = byteBuffer.getShort(baseOffset + 10);
                short dataC = byteBuffer.getShort(baseOffset + 12);
                
                // 应用比例因子
                ua[dataCount] = dataA * xsa;
                ub[dataCount] = dataB * xsb;
                uc[dataCount] = dataC * xsc;
                
                dataCount++;
            }
        }
        
        logger.info("成功读取 {} 个数据点", dataCount);
        
        return new ComtradeData(ua, ub, uc, dataCount, outputSampleRate);
    }
    
    /**
     * 使用默认参数读取1.dat文件 - 对应C代码中的smp_data_init函数
     * @param filename 文件名
     * @return COMTRADE数据对象
     * @throws IOException 文件读取异常
     */
    public static ComtradeData readDefault(String filename) throws IOException {
        // 使用C代码中的默认参数
        float[] xs = {0.062256f, 0.062250f, 0.062262f};
        int inputSampleRate = 256;
        int outputSampleRate = 128;
        int maxSamples = 10000;  // MAX_SMP_DATA_LEN的合理值
        int recordSize = 14;     // C代码中dev=1，所以使用14字节/记录
        
        return readComtradeFile(filename, xs[0], xs[1], xs[2], 
                              inputSampleRate, outputSampleRate, maxSamples, recordSize);
    }
    
    /**
     * 检查DAT文件是否存在
     * @param filename 文件名
     * @return 文件是否存在
     */
    public static boolean isDatFileExists(String filename) {
        return new File(filename).exists();
    }
    
    /**
     * 获取DAT文件信息
     * @param filename 文件名
     * @return 文件信息字符串
     */
    public static String getDatFileInfo(String filename) {
        File file = new File(filename);
        if (!file.exists()) {
            return "文件不存在: " + filename;
        }
        
        long fileSize = file.length();
        int recordCount20 = (int)(fileSize / 20);
        int recordCount14 = (int)(fileSize / 14);
        
        return String.format("文件: %s, 大小: %d 字节, 可能记录数: %d (20字节/记录) 或 %d (14字节/记录)", 
                           filename, fileSize, recordCount20, recordCount14);
    }
}