package com.bcxin.Infrastructures.utils;

import com.bcxin.Infrastructures.exceptions.BadTenantException;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class URLUtil {
    public static String encode(String url) {
        if (!StringUtils.hasLength(url)) {
            return url;
        }

        String path = url;
        String queryPath = null;
        if (url.contains("?")) {
            path = url.substring(0, url.indexOf("?"));
            queryPath = url.substring(url.indexOf("?") + 1);
        }
        List<String> sectionPaths =
                Arrays.stream(path.split("/")).collect(Collectors.toList());
        StringBuilder urlEncoded = new StringBuilder();
        for (int index = 0; index < sectionPaths.size(); index++) {
            String sectionValue = sectionPaths.get(index);
            if (index > 3) {
                sectionValue = encodeValue(sectionValue);
            }

            urlEncoded.append(sectionValue);
            if (index != sectionPaths.size() - 1) {
                urlEncoded.append("/");
            }
        }


        if (StringUtils.hasLength(queryPath)) {
            String[] querySectionPaths = queryPath.split("&");
            for (int index = 0; index < querySectionPaths.length; index++) {
                if (index == 0) {
                    urlEncoded.append("?");
                }
                if (index % 2 == 0) {
                    urlEncoded.append(querySectionPaths[index]);
                    urlEncoded.append("=");
                } else {
                    urlEncoded.append(encodeValue(querySectionPaths[index]));
                    if (index != querySectionPaths.length - 1) {
                        urlEncoded.append("&");
                    }
                }
            }
        }

        return urlEncoded.toString();
    }

    private static String encodeValue(String value)
    {
        try {
            return URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();

            throw new BadTenantException(String.format("地址(%s)编码无效!", value));
        }
    }

    public static String decodeValue(String value) {
        try {
            return URLDecoder.decode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return value;
    }
}
