package com.example.iot_controlhost.utils;

import android.os.Environment;

import com.example.iot_controlhost.model.Log;
import com.example.iot_controlhost.model.sensor.Sensor;
import com.example.iot_controlhost.utils.global.HardwareSetting;
import com.example.iot_controlhost.utils.global.RoomSensor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 将传感器数据保存为csv文件
 *
 * @Author: DuanKaiji
 * @Date: 2023年12月1日 17:18:43
 */
public class CsvConverter {
    public static void saveSensorDataToCsv() {
        List<Sensor> sensorList = RoomSensor.getAllAvailableSensors();

        for (Sensor sensor : sensorList) {
//            writeToCsvFile(sensor.getHistoryData());
        }
    }

    private static void writeToCsvFile(List<Sensor> sensors) {
        try {
            if (sensors.isEmpty()) {
                return;
            }
            Sensor sensor = sensors.get(0);
            //将通用信息作为文件名
            String fileName = sensor.getName() + "型号：" + sensor.getModel()
                    + "_截至：" + MyUtil.getDateDay() + ".csv";
            File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloadDir, fileName);
            FileWriter writer = new FileWriter(file, false);

            List<Field> allFields = new ArrayList<>();
            // 1.获取自己类的属性
            Field[] fields = sensor.getClass().getDeclaredFields();
            allFields.addAll(Arrays.asList(fields));

            // 手动选择要保留的传感器父类属性
            List<String> sensorFieldsToKeep = Arrays.asList("lastRecordTime");
            // 2.获取父类的属性
            Field[] superClassFields = sensor.getClass().getSuperclass().getDeclaredFields();
            for (Field field : superClassFields) {
                if (sensorFieldsToKeep.contains(field.getName())) {
                    allFields.add(field);
                }
            }
            // 手动选择要保留的设备祖父类属性
            List<String> deviceFieldsToKeep = Arrays.asList("failTimes");
            // 3.获取祖父类的属性
            Class<?> grandParentClass = sensor.getClass().getSuperclass().getSuperclass();
            Field[] grandParentFields = grandParentClass.getDeclaredFields();
            for (Field field : grandParentFields) {
                if (deviceFieldsToKeep.contains(field.getName())) {
                    allFields.add(field);
                }
            }
            // 写入表头
            StringBuilder header = new StringBuilder();
            for (Field field : allFields) {
                header.append(field.getName()).append(", ");
            }
            header.delete(header.length() - 2, header.length());
            header.append("\n");
            writer.write(header.toString());

            // 写入数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Sensor s : sensors) {
                StringBuilder csvRow = new StringBuilder();
                for (Field field : allFields) {
                    field.setAccessible(true);
                    Object value = field.get(s);
                    if (value != null) {
                        // 如果是 lastRecordTime 属性，则将时间戳转换为时间字符串
                        if (field.getName().equals("lastRecordTime") && value instanceof Long) {
                            long timestamp = (Long) value;
                            String formattedDate = dateFormat.format(new Date(timestamp));
                            csvRow.append(formattedDate).append(", ");
                        } else {
                            csvRow.append(value).append(", ");
                        }
                    } else {
                        csvRow.append("null, ");
                    }
                }
                csvRow.delete(csvRow.length() - 2, csvRow.length());
                csvRow.append("\n");

                writer.write(csvRow.toString());
            }
            writer.flush();
            writer.close();
        } catch (IOException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

 public static File writeLogToCsvFile(List<Log> logs) {
        try {
            if (logs.isEmpty()) {
                return null;
            }
            Log log = logs.get(0);
            //将通用信息作为文件名
            String fileName =  HardwareSetting.getHostId() + "_log_截至" + MyUtil.getDateDay() + ".txt";
            File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File file = new File(downloadDir, fileName);
//            FileWriter writer = new FileWriter(file, false);

            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(fos, StandardCharsets.UTF_8);

            List<Field> allFields = new ArrayList<>();
            // 获取自己类的属性
            Field[] fields = log.getClass().getDeclaredFields();
            allFields.addAll(Arrays.asList(fields));
            // 写入表头
            StringBuilder header = new StringBuilder();
            for (Field field : allFields) {
                header.append(field.getName()).append(", ");
            }
            header.delete(header.length() - 2, header.length());
            header.append("\n");
            writer.write(header.toString());

            // 写入数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Log s : logs) {
                StringBuilder csvRow = new StringBuilder();
                for (Field field : allFields) {
                    field.setAccessible(true);
                    Object value = field.get(s);
                    if (value != null) {
                        // 如果是 datetime 属性，则将时间戳转换为时间字符串
                        if (field.getName().equals("datetime") && value instanceof Long) {
                            long timestamp = (Long) value;
                            String formattedDate = dateFormat.format(new Date(timestamp));
                            csvRow.append(formattedDate).append(", ");
                        } else {
                            csvRow.append(value).append(", ");
                        }
                    } else {
                        csvRow.append("null, ");
                    }
                }
                csvRow.delete(csvRow.length() - 2, csvRow.length());
                csvRow.append("\n");

                writer.write(csvRow.toString());
            }
            writer.flush();
            writer.close();
            return file;
        } catch (IOException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


}