package me.qwq.doghouse.validator;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.extern.slf4j.Slf4j;
import me.qwq.doghouse.entity.config.SiteConfig;

@Slf4j
public class SiteConfigValidator implements IValidator, ConstraintValidator<SiteConfigValid, SiteConfig> {

    @Override
    public boolean isValid(SiteConfig value, ConstraintValidatorContext context) {
        return true;
    }
    
    /**
     * 检查文件上传路径并返回
     * @param uploadPathStr
     * @return
     */
    public static Path checkUploadPath(String uploadPathStr) {
        if (StringUtils.isBlank(uploadPathStr)) {
            throw new RuntimeException("路径不允许为空");
        }
        Path uploadPath;
        try {
            uploadPath = Paths.get(uploadPathStr);
        }
        catch (Exception e) {
            throw new RuntimeException("非法的文件上传路径", e);
        }
        if (!Files.exists(uploadPath)) {
            try {
                Files.createDirectories(uploadPath);
            }
            catch (IOException e) {
                throw new RuntimeException("创建文件上传路径失败", e);
            }
        }
        else if (!Files.isDirectory(uploadPath)) {
            throw new RuntimeException("文件上传路径已存在，但非目录");
        }

        if (!Files.isReadable(uploadPath) || !Files.isWritable(uploadPath)) {
            throw new RuntimeException("文件上传路径读写权限获取失败");
        }
        
        return uploadPath;
    }

}
