package com.fs.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
@Slf4j
@Service
public class FileCacheService {

    @Value("${getTuiImg:''}")
    private String getTuiImg;

    @Value("${getTuiFont:''}")
    private String getTuiFont;

    @Value("${tuiImgCache:0}")
    private String tuiImgCache;

    private byte[] templateBytes;
    private byte[] fontBytes;
    @PostConstruct
    public void init() {
        if(StringUtils.equals("1", tuiImgCache)) {
            try {
                // 检查配置是否为空
                if (StringUtils.isNotBlank(getTuiImg) && Files.exists(Paths.get(getTuiImg))) {
                    this.templateBytes = Files.readAllBytes(Paths.get(getTuiImg));
                } else {
                    log.warn("模板图片路径为空或文件不存在: {}", getTuiImg);
                }

                if (StringUtils.isNotBlank(getTuiFont) && Files.exists(Paths.get(getTuiFont))) {
                    this.fontBytes = Files.readAllBytes(Paths.get(getTuiFont));
                } else {
                    log.warn("字体文件路径为空或文件不存在: {}", getTuiFont);
                }
            } catch (Exception e) {
                log.error("文件缓存初始化异常，应用将继续启动: {}", e.getMessage(), e);
            }
        }
    }


    /**
     * 获取模板图片的 InputStream
     */
    public InputStream getTemplateStream() {
        return new ByteArrayInputStream(templateBytes);
    }

    /**
     * 获取字体文件的 InputStream
     */
    public InputStream getFontStream() {
        return new ByteArrayInputStream(fontBytes);
    }

    // 可选：提供重新加载方法（如需热更新）
    public void reload() throws IOException {
        this.templateBytes = Files.readAllBytes(Paths.get(getTuiImg));
        this.fontBytes = Files.readAllBytes(Paths.get(getTuiFont));
    }
}
