package cn.reghao.oss.store.service;

import cn.reghao.oss.store.util.FileType;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.oss.api.constant.SupportedMedia;
import cn.reghao.oss.api.constant.UploadChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @author reghao
 * @date 2023-07-10 17:03:55
 */
@Slf4j
@Service
public class ChannelValidateService {
    public Result validate(File file, int channelId) {
        UploadChannel channel = UploadChannel.getUploadChannel(channelId);
        switch (channel) {
            case disk:
                return Result.success();
            case video:
                return validateVideo(file);
            case audio:
                return validateAudio(file);
            case avatar:
                return validateImage(file, UploadChannel.avatar.getMaxSize());
            case image:
            case img:
                return validateImage(file, UploadChannel.image.getMaxSize());
            case photo:
                return validateImage(file, UploadChannel.photo.getMaxSize());
            default:
                String errMsg = String.format("%s 的文件暂时无法处理", channel.getPrefix());
                return Result.fail(errMsg);
        }
    }

    private Result validateVideo(File file) {
        String mediaType = FileType.getMediaType(file.getAbsolutePath());
        long maxSize = UploadChannel.video.getMaxSize();
        long len = file.length();
        if (len > maxSize) {
            String errMsg = String.format("视频文件大小不能超过 %s bytes", maxSize);
            return Result.fail(errMsg);
        } else if (!mediaType.startsWith("video")) {
            return Result.fail("非视频文件格式");
        }

        return Result.success();
    }

    private Result validateAudio(File file) {
        String mediaType = FileType.getMediaType(file.getAbsolutePath());
        long maxSize = UploadChannel.audio.getMaxSize();
        long len = file.length();
        if (len > maxSize) {
            String errMsg = String.format("音频文件大小不能超过 %s bytes", maxSize);
            return Result.fail(errMsg);
        } else if (!mediaType.startsWith("audio")) {
            return Result.fail("非音频文件格式");
        }

        return Result.success();
    }

    private Result validateImage(File file, long maxSize) {
        String mediaType = FileType.getMediaType(file.getAbsolutePath());
        long len = file.length();
        if (len > maxSize) {
            String errMsg = String.format("图片文件大小不能超过 %s bytes", maxSize);
            return Result.fail(errMsg);
        } else if (!SupportedMedia.imageFormats.contains(mediaType.replace("image/", ""))) {
            String errMsg = String.format("系统仅支持 %s 等图片格式", SupportedMedia.imageFormats);
            return Result.fail(errMsg);
        }

        return Result.success();
    }
}
