package com.bcxin.identify.util.file.oss;

import com.aliyun.oss.internal.Mimetypes;
import com.aliyun.oss.model.ObjectMetadata;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * 
 * <b>Aliyun oss对象存储服务</b>
 * 
 * @author LuoPeng
 * @date 2016年12月14日 下午9:53:18
 * @注意事项 </b>
 * <b>
 */
public class OSSUtil {
	
	public static String getFileType(String fileName) {
		return "*." + fileName.split("\\.")[0];
	}

	public static String getDirectoryName(String filePath) {
		if (filePath.indexOf("/") == 0) {
			filePath = filePath.substring(1);
		}
		return filePath.replace("/" + filePath.split("/")[0], "");
	}

	public static String getName(String filePath) {
		return filePath.split("/")[0];
	}

	public static ObjectMetadata getObjectMetadata(String file) {
		Mimetypes mime = Mimetypes.getInstance();
		String contentType = file.indexOf(".") == -1 ? "application/octet-stream"
				: mime.getMimetype(file);
		ObjectMetadata meta = new ObjectMetadata();
		meta.setContentEncoding("UTF-8");
		meta.setContentType(contentType);
		if ((contentType.contains("image")) || (contentType.contains("text"))
				|| (contentType.contains("html"))) {
			meta.setContentDisposition("attachment=41975");
		}
		return meta;
	}

	public static String createUUIDUrl(String directory, String srcFileName) {
		String fileFix = srcFileName.split("\\.").length >= 2 ? srcFileName
				.split("\\.")[(srcFileName.split("\\.").length - 1)] : null;
		if (fileFix == null) {
			return directory + UUID.randomUUID().toString().replace("-", "");
		}
		return directory + UUID.randomUUID().toString().replace("-", "") + "."
				+ fileFix;
	}

	public static String createDateUrl(String directory, String srcFileName) {
		String fileFix = srcFileName.split("\\.").length >= 2 ? srcFileName
				.split("\\.")[(srcFileName.split("\\.").length - 1)] : null;
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmssS");
		String date = sFormat.format(calendar.getTime());
		if (fileFix == null) {
			return directory + date;
		}
		return directory + date + "." + fileFix;
	}
}
