#include "device_fileopen.h"
#include "device_id_change.h"
#include "common.h"

#define FILENAME PROJECT_ROOT_DIR "/Deviceld.txt"  

#define FILE_VERSION PROJECT_ROOT_DIR "/version.conf"

static char *s_device_id = NULL;//设备的类型的id

/*读出文件函数，读取设备号函数，获得设备号id*/
char *device_inspect() {
    FILE *file;
    static char s_buffer_device[30]; // 用于存储文件内容
    char *read_device_back_fail_middle=read_device_back_fail();    
    while (1) {
        file = fopen(FILENAME, "r"); // 以只读模式打开文件

        if (file == NULL) {
             if(read_device_back_fail_middle!=NULL) {//回退文件
             return read_device_back_fail_middle;
            }
           my_zlog_info("文件 %s 打开失败，等待中...", FILENAME);
        } 
        else {
            // 尝试读取文件内容
            if (fgets(s_buffer_device, sizeof(s_buffer_device), file) != NULL) {
                size_t len = strlen(s_buffer_device);
                if (len > 0 && s_buffer_device[len - 1] == '\n') {
                    s_buffer_device[len - 1] = '\0';
                }
                fclose(file);
               my_zlog_info("读取到文件内容: %s", s_buffer_device);
                return  s_buffer_device;
            } else {
                 if(read_device_back_fail_middle!=NULL) {
                     fclose(file);
                     return read_device_back_fail();
                 }
               my_zlog_info("文件为空，等待中...");
            }
            fclose(file);
        }
    delay_s(1); // 等待1秒后再次检查
    }
}

/*设备读取文件初始化*/
int device_id_file_init() {
    s_device_id=device_inspect();
    return 0;
}
char *device_id_function(){
    return s_device_id;
}

/*打开版本文件，版本文件是go语言进行创建，只需要读取就行了*/
char *program_version() {
    FILE *file;
    static char s_buffer_version[30] = "unknown";

    file = fopen(FILE_VERSION, "r");
    if (file == NULL) {
        my_zlog_debug("版本文件无");
        return s_buffer_version;
    }

    if (fgets(s_buffer_version, sizeof(s_buffer_version), file) != NULL) {
        size_t len = strlen(s_buffer_version);
        if (len > 0 && s_buffer_version[len - 1] == '\n') {
            s_buffer_version[len - 1] = '\0';
        }
        fclose(file);
        my_zlog_debug("读取到文件内容: %s", s_buffer_version);
        return s_buffer_version;
    }

    fclose(file);
    my_zlog_debug("文件为空，等待中...");
    return s_buffer_version;
}