package com.duiba.tuia.youtui.web.tool;/**
 * Created by chengdeman .
 * 17/6/27 .
 */

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 域名处理工具类
 *
 * @author chengdeman
 * @create 2017-06-27 上午9:46
 **/
public class DomainUtil {

    private DomainUtil() {
    }

    // 定义正则表达式，域名的根需要自定义
    private static final String RE_TOP = "[\\w-]+\\.(com.cn|net.cn|gov.cn|org\\.nz|org.cn|com|net|xyz|org|gov|cc|biz|info|cn|co)\\b()*";



    /**
     * 获取顶级域名
     * @param url URL
     * @return
     */
    public static String getTopDomain(String url) {

        String result = url;
        Pattern pattern = Pattern.compile(RE_TOP , Pattern.CASE_INSENSITIVE);
        try {
            Matcher  matcher = pattern.matcher(url);
            matcher.find();
            result = matcher.group();
        } catch (Exception e) {
            return "tuia.cn" ;
        }
        return result;
    }


    /**
     * 替换当前路径下的域名
     * @return
     */
    public static String replaceDomain(String target, String replacement){

        if (Environment.isOnline() || Environment.isPrepub()) {//只在线上，预发环境上生效
            if (target == null || replacement == null) {
                return target;
            }

            if (target.contains("yun.duiba.com.cn")) {
                target = target.replace("yun.duiba.com.cn", replacement);
            }

            if (!replacement.equals("yun.tuia.cn")) {
                target = target.replace("yun.tuia.cn", replacement);
            }
        }
        return target;

    }

    /**
     * 获取当前请求
     * @param request
     * @return
     */
    public static String getCurrentYunDomain(HttpServletRequest request) {
        return "yun." + getTopDomain(request.getServerName());
    }

    public static String getHost(HttpServletRequest request) {

        try {
            if (Environment.isOnline() || Environment.isPrepub()) {
                return "//" + getCurrentYunDomain(request);
            } else {
                return "//yun.dui88.com";
            }
        } catch (Exception e) {//以防万一
            return "//yun.tuia.cn";
        }
    }
}
