package cn.util.file;

import java.io.File;
import java.io.FilenameFilter;
import org.springframework.web.multipart.MultipartFile;
import cn.common.exception.file.FileSizeLimitExceededException;
import cn.common.exception.file.InvalidExtensionException;
import cn.util.http.MimeTypeKit;

//用来过滤文件
public class FileFilter implements FilenameFilter
{
	/**默认大小 50M*/
	public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
	/** 默认的文件名最大长度 100*/
	public static final int DEFAULT_FILE_NAME_LENGTH = 100;
	
	private String name;
	private String extension;

	public FileFilter(String name, String extension) {
		this.name = name;
		this.extension = extension;
	}

	public boolean accept(File dir, String filename) {
		boolean fileOK = true;
		if (name == "*"&&extension=="*") {
			return fileOK = true;

		}
		if (name != null) {
			// 不大解理"&="的运行过程,
			fileOK &= filename.startsWith(name);

		}
		if (extension != null) {
			fileOK &= filename.endsWith('.' + extension);
		}
		return fileOK;
	}
	

	/**
	 * 文件大小校验
	 * @param file 上传的文件
	 * @return
	 * @throws FileSizeLimitExceededException 如果超出最大大小
	 * @throws InvalidExtensionException
	 */
	public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
			throws FileSizeLimitExceededException, InvalidExtensionException {
		long size = file.getSize();
		if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
			throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
		}

		String fileName = file.getOriginalFilename();
		String extension = FileTypeKit.getExtension(file);
		if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
			if (allowedExtension == MimeTypeKit.IMAGE_EXTENSION) {
				throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
						fileName);
			} else if (allowedExtension == MimeTypeKit.FLASH_EXTENSION) {
				throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
						fileName);
			} else if (allowedExtension == MimeTypeKit.MEDIA_EXTENSION) {
				throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
						fileName);
			} else {
				throw new InvalidExtensionException(allowedExtension, extension, fileName);
			}
		}
	}

	/**判断MIME类型是否是允许的MIME类型*/
	public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
		for (String str : allowedExtension) {
			if (str.equalsIgnoreCase(extension)) {
				return true;
			}
		}
		return false;
	}

}
