package com.brilliance.isc.doc.configload;

import com.brilliance.isc.common.tools.service.ObjectStroeToolService;
import freemarker.cache.TemplateLoader;

import java.io.*;

public class RealtimeFileTemplateLoader implements TemplateLoader {

    private final String templateUrl;

    private ObjectStroeToolService objectStoreService;

    public RealtimeFileTemplateLoader(String templateUrl, ObjectStroeToolService objectStoreService) {
        this.templateUrl = templateUrl;
        this.objectStoreService = objectStoreService;
    }

    @Override
    public Object findTemplateSource(String name) throws IOException {
        //云存储是否存在文件
        String path = new StringBuffer(templateUrl).append("/").append(name).toString();
        return objectStoreService.isExistObjectFile(path) ? objectStoreService.getObjectFile(path) : null;
    }

    @Override
    public long getLastModified(Object templateSource) {
        File file = (File) templateSource;
        return file.lastModified();
    }

    @Override
    public Reader getReader(Object templateSource, String encoding) throws IOException {
        if (null == templateSource) {
            return null;
        }
        File file = (File) templateSource;
        try {
            return new InputStreamReader(new FileInputStream(file), encoding);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("Error reading template file: ", e);
        }
    }

    @Override
    public void closeTemplateSource(Object templateSource) throws IOException {
        // Nothing to close here
    }
}
