package cn.ey.biz.module.system.service.file;

import cn.ey.biz.common.exception.ServiceException;
import cn.ey.biz.module.system.enums.ErrorCodeConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class FileTypeCheck {

    static final Pattern pattern = Pattern.compile("^.+\\.(\\w+)$");

    // black list
    // exe
    static final String[] validTypes = {"application/x-msdownload"};

    public static void checkFileByActualType(MultipartFile mFile, String[] customTypes) {
        Tika defaultTika = new Tika();
        try {
            if (!isValidFileType(defaultTika.detect(mFile.getInputStream()), customTypes)) {
                throw new ServiceException(ErrorCodeConstants.FILE_TYPE_EXCEPTION);
            }
        } catch (IOException e) {
            log.error("getFileTypeByFileName exception:", e);
        }
    }

    public static void checkFileBySuffixes(MultipartFile file, String[] customTypes) {
        Matcher m = pattern.matcher(Objects.requireNonNull(file.getOriginalFilename().toLowerCase()));
        if (m.find()) {
            if (!Arrays.asList(customTypes).contains(m.group(1))) {
                throw new ServiceException(ErrorCodeConstants.FILE_TYPE_EXCEPTION);
            } else {
                return;
            }
        }
        throw new ServiceException(ErrorCodeConstants.FILE_TYPE_EXCEPTION);
    }

    private static boolean isValidFileType(String fileType, String[] customTypes) throws IOException {
        for (String type : validTypes) {
            if (fileType.equals(type)) {
                return false;
            }
        }
        for (String type : customTypes) {
            if (fileType.equals(type)) {
                return false;
            }
        }
        return true;
    }

}

