package com.wisedu.coeus.util;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.coeus.helper.ApplicationHelper;
import com.wisedu.coeus.web.AppConfig;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 01112026 on 15-1-22.
 */
public class UrlUtils {

    /**
     * 格式化HTTP地址
     * 格式化为http://host/path
     * @param url
     * @return
     */
    public static String fromatHttpUrl(String url) {
        if (Strings.isEmpty(url)) return "";

        if (! url.contains("://")) {
            url = "http://".concat(url);
        }
        while (url.endsWith("/")) {
            url = url.substring(0, url.length() - 1);
        }

        return url;
    }

    /**
     * 获取主机地址，含应用名称
     * @param request
     * @return
     */
    public static String getCurrentSiteUrl(HttpServletRequest request) {
        String url = request.getScheme().concat("://").concat(getHostName(request));
        url = url.concat(ApplicationHelper.getContextPath());

        return url;
    }

    /**
     * 获取主机地址，不含应用名称
     * @param request
     * @return
     */
    public static String getHostUrl(HttpServletRequest request) {
        String url = request.getScheme().concat("://").concat(getHostName(request));

        return url;
    }

    /**
     * 地址解码
     * @param text
     * @param encoding
     * @return
     */
    public static String decode(String text, String encoding) {
        String decodeText = null;
        try {
            decodeText = URLDecoder.decode(text, encoding);
        } catch (Exception e){

        }

        return decodeText;
    }

    public static String decode(String text) {
        String decodeText = null;
        try {
            decodeText = URLDecoder.decode(text, "UTF-8");
        } catch (Exception e){

        }

        return decodeText;
    }

    /**
     * 地址编码
     * @param text
     * @param encoding
     * @return
     */
    public static String encode(String text, String encoding) {
        String encodeText = null;
        try {
            encodeText = URLEncoder.encode(text, encoding);
        } catch (Exception e){

        }

        return encodeText;
    }

    public static String encode(String text) {
        String encodeText = null;
        try {
            encodeText = URLEncoder.encode(text, "UTF-8");
        } catch (Exception e){

        }

        return encodeText;
    }

    private static String HEX_STR =  "0123456789ABCDEF";

    public static String encodeNonAscii(String text, boolean onlyNonAscii) {
        try {
            StringBuffer buffer = new StringBuffer(1024);
            char ch[] = text.toCharArray();
            char c;
            for (int i=0;i<ch.length;i++) {
                c = ch[i];
                if (c >= '\u0080') {
                    buffer.append(URLEncoder.encode(String.valueOf(c), "UTF-8"));
                } else if (c == '*' || c == '/' || c == '\\' || c == '|' || c == '+' || c == '?') {
                    buffer.append("%");
                    buffer.append(HEX_STR.charAt((c&0xF0)>>4));
                    buffer.append(HEX_STR.charAt((c&0x0F)));
                } else {
                    buffer.append(c);
                }
            }
            return buffer.toString();
        } catch (Exception ex) {
            return text;
        }
    }

    /**
     * 获取附件头中的文件名称，自动适配浏览器差异
     * @param name
     * @param request
     * @return
     */
    public static String getContentDispositionName(String name, HttpServletRequest request) {
        String userAgent = Strings.trimToEmpty(request.getHeader("User-Agent")).toLowerCase();
        try {
        if (userAgent.indexOf("firefox") > -1) {
            name = new String(name.getBytes("GBK"), "ISO8859-1");
        } else {
            name = URLEncoder.encode(name, "UTF-8");
        }
        } catch (Exception e) {
        }

        return name;
    }

    /**
     * 获取主机头，为了躲过阿里云备案的策略，在代理访问时增加X-Real-Host来标识原始的主机头
     * @param request
     * @return
     */
    public static String getHostName(HttpServletRequest request) {
        String hostName = request.getHeader("X-Real-Host");
        if (Strings.isEmpty(hostName)) {
            hostName = request.getHeader("Host");
        }
        return hostName;
    }

    /**
     * 重定向
     * 1、对于绝对路径直接重定向
     * 2、对于相对本应用路径，会自动处理增加ContextPath所以不必增加ContextPath
     * @param request
     * @param response
     * @param redirectUrl
     * @throws IOException
     */
    public static void redirect(HttpServletRequest request, HttpServletResponse response, String redirectUrl) throws IOException {
        String url = redirectUrl.toLowerCase();
        if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("ftp://")) {
            response.sendRedirect(redirectUrl);
            return;
        }
        url = getCurrentSiteUrl(request);
        if (redirectUrl.startsWith("/") || redirectUrl.startsWith("\\")) {
            url = url.concat(redirectUrl);
            response.sendRedirect(url);
            return;
        }
    }

    /**
     * 判断当前是否移动端访问
     * @param request
     * @return
     */
    public static boolean isMobile(HttpServletRequest request){
    	String userAgent = request.getHeader("User-Agent");

        Pattern pattern;
        Matcher matcher;

        boolean mobile = false;

        pattern = Pattern.compile("Android[ \\/]([\\d\\.]+)|iPhone|iPad|Windows Phone|Mobile", Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(userAgent);
        if (matcher.find()) {
            mobile = true;
        }
        
        return mobile;
    }
    
    /**
     * 格式化网址前缀部分
     * 格式：http://domain/path
     */
    public static String formatUrlPrefix(String url) {
        if (Strings.isEmpty(url)) return "";

        if (! url.contains("://")) {
            url = "http://".concat(url);
        }
        if (! url.endsWith("/")) {
            url = url.concat("/");
        }

        return url;
    }
    
}
