package org.lym.pom.service.impl;

import cn.hutool.core.io.FileUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.lym.pom.service.ImageStorageService;
import org.lym.pom.util.github.GitHubFileUtil;
import org.lym.pom.util.github.dto.GithubFileAndCommit;
import org.lym.pom.util.github.dto.GithubFileInfo;
import org.shoulder.core.context.AppContext;
import org.shoulder.core.context.AppInfo;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;

//@Service
public class GithubImageStorageService implements ImageStorageService {
    private static final String prefix = GitHubFileUtil.GITHUB_REPOSITORY_API_URL + GitHubFileUtil.APP_NAME + "/";

    @SneakyThrows @Override public String uploadImage(MultipartFile file) {
        // todo valid contentType
        byte[] imageBytes = file.getBytes();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        int hash = uuid.hashCode() % 1000;
        String contentTypePart = URLEncoder.encode(Objects.requireNonNull(file.getContentType()), AppInfo.charset());
        String targetPath = GitHubFileUtil.APP_NAME + "/" + hash + "/" + contentTypePart + "/" + uuid + "." + FileUtil.extName(
                file.getOriginalFilename());
        GithubFileAndCommit response = GitHubFileUtil.uploading(targetPath, base64Image, AppContext.getUserId());
        return response.getContent().getDownload_url();
    }

    @SneakyThrows @Override public void downloadImage(String resourceIdOrPath, HttpServletResponse response) {
        String githubDownloadUrl = prefix + parseGithubPath(resourceIdOrPath);
        response.sendRedirect(githubDownloadUrl);
        // 设置响应头并输出图片流, 根据实际情况设置内容类型);
        //response.setContentType();
        //IoUtil.copy(imageStream, response.getOutputStream());
    }

    public String parseContentType(String resourceIdOrPath) {
        String[] parts = parseGithubPath(resourceIdOrPath).split("/");
        return parts[1];
    }

    public String parseGithubPath(String resourceIdOrPath) {
        //GithubConfig config = new GithubConfig();
        if (resourceIdOrPath.startsWith("https://raw.githubusercontent.com")) {
            // github.raw
            //https://raw.githubusercontent.com/ChinaLym/images/main/7b25/**/940768d249a1bdc5b43ab1b65bdf.png
            String suffix = resourceIdOrPath.replaceFirst(prefix, "");
            return suffix;
        }
        return resourceIdOrPath;
    }

    @Override public boolean deleteImage(String resourceIdOrPath) {
        GithubFileInfo githubFileInfo = GitHubFileUtil.queryFile(resourceIdOrPath);
        String path = githubFileInfo.getPath();
        // 暂时只允许管理员删除
        // todo 校验 git commit message 中上传人是否一致，避免将其他人删掉
        GithubFileAndCommit deleteResp = GitHubFileUtil.delFile(path, githubFileInfo.getSha(), "UPLOAD_API");
        return true;
    }
}
     