package com.bonus.file.service;

import com.bonus.file.utils.FileDownloadUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.bonus.file.utils.FileUploadUtils;

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

/**
 * 本地文件存储
 * 
 * @author bonus
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService
{
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     * 
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String name = FileUploadUtils.upload(localFilePath, file);
        String url = domain + localFilePrefix + name;
        return url;
    }

    @Override
    public boolean downloadFile(String urlStr, String destination) throws Exception
    {
        return FileDownloadUtils.downloadFile(urlStr, destination);
    }


    @Override
    public boolean deleteFile(String urlStr) throws Exception
    {
        String regex = String.format("^(.*?%s)", localFilePrefix);
        String updatePath = urlStr.replaceFirst(regex, localFilePath);
        Path path = Paths.get(updatePath);
        if (Files.exists(path)){
            try {
                Files.deleteIfExists(path);
            }catch (IOException e){
                throw new Exception(e.getMessage(), e);
            }
        }else {
            throw new Exception("删除文件时文件不存在");
        }
        return true;
    }
}
