package com.apobates.forum.attention.core;

import java.util.Optional;
/**
 * 头像图片的路径句柄
 * Schema(avtar://)
 * @author xiaofanku
 * @since 20190307
 */
public class AvatarImagePathConvertHandler implements ImagePathDecodeHandler,ImagePathEncodeHandler{
	private final ImageStorePath storePath;
	//avtar://
	public AvatarImagePathConvertHandler(ImageStorePath storePath) {
		super();
		this.storePath = storePath;
	}
	
	@Override
	public Optional<String> decode(String dbAvatarPath, ImageDirectoryEnum directoryEnum, String scale) {
		if(null==directoryEnum) {
			return Optional.empty();
		}
		if(ImageDirectoryEnum.DEFAT == directoryEnum) {
			return Optional.of(dbAvatarPath.replaceAll("avtar://defat", storePath.getDefaultImagePath())); //http://xx.com/avatar
		}
		if(ImageDirectoryEnum.LOCAL == directoryEnum) {
			return Optional.of(dbAvatarPath.replaceAll("avtar://local", storePath.getLocalImagePath()));
		}
		if(ImageDirectoryEnum.REMOT == directoryEnum) {
			return Optional.of(dbAvatarPath.replaceAll("avtar://remot", storePath.getRemoteImagePath()));
		}
		return Optional.empty();
	}

	@Override
	public Optional<String> encode(String fileNamePath, ImageDirectoryEnum directoryEnum) {
		return Optional.of("avtar://" + directoryEnum.name().toLowerCase() + fileNamePath);
	}
	
	/**
	 * 返回默认头像编码中的文件路径
	 * 默认头像为系统提供的头像
	 * @param encodeAvtarFormatPath 默认头像编码的路径,例:avtar://defat/default/0.png
	 * @return 若参数等于: avtar://defat/default/0.png 返回 /default/0.png
	 */
	public static String getDefaultAvtarFilePath(String encodeAvtarFormatPath) {
		try {
			return encodeAvtarFormatPath.substring(13);
		}catch(StringIndexOutOfBoundsException e) {
			return encodeAvtarFormatPath; //参数 = /empty.png
		}
	}

}
