package com.shunwang.apitools.util;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

/**
 * @author min.da
 * @since 2016-01-07
 */
public abstract class WebUtils {

    /** 类路径加载的伪URL前缀 */
    public static final String CLASSPATH_URL_PREFIX = "classpath:";

    /**
     * 返回给定的资源位置是否是一个伪URL或者一个标准的URL.
     *
     * @param resourceLocation
     * @return
     * @see #CLASSPATH_URL_PREFIX
     * @see java.net.URL
     */
    public static boolean isUrl(String resourceLocation) {
        if (resourceLocation == null) {
            return false;
        }
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            return true;
        }
        try {
            new URL(resourceLocation);
            return true;
        }
        catch (MalformedURLException ex) {
            return false;
        }
    }

    /**
     * 解析给定资源为一个URL
     *
     * @param resourceLocation
     * @return 一个对应的URL对象
     * @throws FileNotFoundException
     */
    public static URL getURL(String resourceLocation) throws FileNotFoundException {
        if (resourceLocation == null) {
            throw new IllegalArgumentException("资源位置不能为null");
        }
        if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
            String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
            URL url = getDefaultClassLoader().getResource(path);
            if (url == null) {
                throw new FileNotFoundException("给定类路径资源[" + path + "]不存在");
            }
            return url;
        }
        try {
            return new URL(resourceLocation);
        }
        catch (MalformedURLException ex) {
            try {
                return new File(resourceLocation).toURI().toURL();
            }
            catch (MalformedURLException ex2) {
                throw new FileNotFoundException("[" + resourceLocation + "]既不是一个URL也不是一个文件路径");
            }
        }
    }

    /**
     * 返回指定路径在Web应用程序中的真实路径
     * @param servletContext
     * @param path
     * @return
     * @throws FileNotFoundException
     */
    public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
        if (servletContext == null) {
            throw new IllegalArgumentException("ServletContext不能为null");
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        String realPath = servletContext.getRealPath(path);
        if (realPath == null) {
            throw new FileNotFoundException(
                    "资源[" + path + "]无法解析为绝对文件路径");
        }
        return realPath;
    }

    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        }
        catch (Throwable ex) {
        }
        if (cl == null) {
            cl = WebUtils.class.getClassLoader();
        }
        return cl;
    }

    public static String getQueryString(Map<String, String> params) {
        if (params == null || params.isEmpty()) return null;

        StringBuilder sb = new StringBuilder();
        boolean first = true;

        for (Map.Entry<String, String> e : params.entrySet()) {
            String name = e.getKey();
            String value = e.getValue();
            if (!first) {
                sb.append("&");
            } else {
                first = false;
            }
            sb.append(name).append("=").append(value);
        }
        return sb.toString();
    }

}
