package me.qwq.doghouse.config;

import java.nio.file.Paths;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.info.BuildProperties;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import lombok.Data;
import lombok.experimental.Accessors;
import me.qwq.doghouse.BlogApplication;
import me.qwq.doghouse.entity.Asset;

@Data
@Accessors(chain = true)
@ConfigurationProperties(prefix = "doghouse")
@Component("doghouseProperties")
public class DoghouseProperties {
    
    @Autowired
    BuildProperties buildProperties;
    
    String workPath = "/tmp/doghouse/";
    
    /**
     * 文件上传路径。默认是相对于 workPath 的路径。如需绝对路径请在前加 absolute:
     */
    String fileUploadPath = "/upload/";
    
    /**
     * 文件在 SQL 中存储的路径前缀
     * <p>
     * 如：文件名为 filename.file, 则设置为 /upload/ 时, 可通过 http(s)://siteAddress/upload/{年份}/{月份}/filename.file 访问到文件
     */
    String fileSqlPath = "/upload/";
    
    /**
     * 数据库 blog.db 路径是否使用相对路径, 默认是
     */
    Boolean useRelativeDbPath = true;
    
    public String getFileUploadPath() {
        String finalPath;
        if (StringUtils.startsWith(fileUploadPath, "absolute:")) {
            finalPath = Paths.get(fileUploadPath.substring("absolute:".length())).toString();
        }
        else {
            finalPath = Paths.get(workPath, fileUploadPath).toString();
        }
        return finalPath + Paths.get("/").toString();
    }
    
    public String getVersion() {
        return buildProperties.getVersion();
    }
    
    public boolean isDebug() {
        return BlogApplication.isDebug();
    }
    
    /**
     * 将资产的 sql 路径转换为实际路径
     * @param asset
     * @return 资产在部署机器上的实际路径
     */
    public String getFileUploadPath(@NonNull Asset asset) {
        String path = asset.getPath();
        if (StringUtils.isNoneBlank(path) && path.startsWith(getFileSqlPath())) {
            path = path.replaceFirst(getFileSqlPath(), getFileUploadPath());
        }
        return path;
    }
    
    public String getFileSqlPath(@NonNull String path) {
        if (StringUtils.isNoneBlank(path) && path.startsWith(getFileUploadPath())) {
            path = path.replaceFirst(getFileUploadPath(), getFileSqlPath());
        }
        return path;
    }

}
