package com.github.novicezk.midjourney.util;

import cn.hutool.core.util.StrUtil;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class OBSUtil {

    private static final String endPoint = "obs.cn-east-2.myhuaweicloud.com";
    private static final String ak = "CROQ0IJRW2FW5NSERZBR";
    private static final String sk = "rAbki4thgWx9iKXendlIH3gvKi8JFHUcVOWwObyS";

    private static final DateTimeFormatter SHORT_MILLISECOND = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");


    public static void listbucket() {
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);

        // 列举桶
        ListBucketsRequest request = new ListBucketsRequest();
        request.setQueryLocation(true);
        List<ObsBucket> buckets = obsClient.listBuckets(request);
        for (ObsBucket bucket : buckets) {
            System.out.println("BucketName:" + bucket.getBucketName());
            System.out.println("CreationDate:" + bucket.getCreationDate());
            System.out.println("Location:" + bucket.getLocation());
        }
    }


    /**
     * 文件上传
     * @param file
     * @param fileType
     * @return
     */
    public static String upload(File file, String fileType, String end) {
        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(ak, sk, end);

        // localfile为待上传的本地文件路径，需要指定到具体的文件名
        PutObjectResult putObjectResult = obsClient.putObject("wuhan-oss-test-002", getObjectKey(file.getName(), fileType), file);
        log.info("华为云返回结果：{}", JSONObject.valueToString(putObjectResult));
        String url = Optional.ofNullable(putObjectResult)
                .map(x -> x.getObjectUrl())
                .orElse("");
        return url;

    }

    /**
     * 组装ObjectKey
     */
    private static String getObjectKey(String fileName, String fileType) {
        fileName = StrUtil.isEmpty(fileName) ? taskName()
                : (formatName(fileName) + "_" + getYmdhmss());
        return new StringBuilder("oss/").append("upload").append("/").append("IMAGE").append("/")
                .append(fileType).append("/").append(fileName).append(".").append(fileType).toString();
    }

    /**
     * 获取当前的日期字符串(yyyyMMddHHmmssSSS)
     *
     * @return
     */
    public static String getYmdhmss() {
        return LocalDateTime.now().format(SHORT_MILLISECOND);
    }

    /**
     * 格式化文件名称，过滤特殊字符(名称太长进行截断)
     *
     * @param fileName
     */
    public static String formatName(String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return null;
        }
        try {
            String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(fileName);
            String result = m.replaceAll("").trim();
            // 文件名称过长的话,限制40个字
            return result.length() > 40 ? result.substring(0, 40) : result;
        } catch (Exception e) {
            log.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
            return taskName();
        }
    }

    /**
     * 生成随机任务名称
     *
     * @return
     */
    public static String taskName() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static void main(String[] args) {
        listbucket();
    }
}
