package cn.freemud.utils;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;

/**
 * Base64扩展工具，生成/解析适合url的Base64编码串。<br>
 * 将"/"替换成"_"，"+"替换成"-"，删除结尾"="
 *
 * @author elric
 */
public class UrlBase64 {

    public static String encode(byte[] src) {
        String base64 = new String(Base64.encodeBase64(src));
        return encodeToUrlCompatibleFormat(base64);
    }

    public static byte[] decode(String src) {
        String base64 = decodeFromUrlCompatibleFormat(src);
        return Base64.decodeBase64(base64.getBytes());
    }

    public static String encodeStr(String src) {
        return encode(src.getBytes(Charset.forName("utf-8")));
    }

    public static String decodeToStr(String src) {
        return new String(decode(src), Charset.forName("utf-8"));
    }

    private static String encodeToUrlCompatibleFormat(String base64) {
        String urlBase64 = base64;
        if (urlBase64.indexOf('=') != -1) {
            urlBase64 = urlBase64.substring(0, urlBase64.indexOf('='));
        }
        urlBase64 = urlBase64.replace('/', '_').replace('+', '-');
        return urlBase64;
    }

    private static String decodeFromUrlCompatibleFormat(String urlBase64) {
        String base64 = urlBase64;
        base64 = base64.replace('_', '/').replace('-', '+');
        int count = base64.length() % 4;
        String suffix = "";
        if (count == 3) {
            suffix = "=";
        } else if (count == 2) {
            suffix = "==";
        }
        base64 += suffix;
        return base64;
    }

}
