package cn.reghao.oss.store.service;

import cn.reghao.oss.storeapi.constant.ObjectType;
import cn.reghao.oss.storeapi.dto.ObjectChannel;
import cn.reghao.oss.store.util.FileType;
import cn.reghao.jutil.jdk.result.Result;
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 validateFile(File file, ObjectChannel objectChannel) {
        int fileType = objectChannel.getFileType();
        ObjectType objectType = ObjectType.getByCode(fileType);
        if (objectType == null) {
            String errMsg = String.format("channel validate failed, file_type %s not exist", fileType);
            return Result.fail(errMsg);
        }

        long maxSize = objectChannel.getMaxSize();
        long len = file.length();
        if (len > maxSize) {
            String errMsg = String.format("channel validate failed, the size of %s file bigger than %s bytes", objectType.name(), maxSize);
            return Result.fail(errMsg);
        }

        String contentType = ObjectType.getDescByCode(fileType);
        String mediaType = FileType.getMediaType(file.getAbsolutePath());
        if (!contentType.equals(ObjectType.Other.getDesc()) && !mediaType.startsWith(contentType)) {
            String errMsg = String.format("channel validate failed, the format of file is not %s", contentType);
            return Result.fail(errMsg);
        }

        return Result.success();
    }
}
