package com.drops.utils;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @ClassName: URLUtil
 * @Description: TODO
 * @Author: Summer
 * @Date: 2021/7/28 9:59
 * @Version: v1.0.0
 * @Description: 对传入的url进行处理
 **/
public class URLUtil {

//    public URLUtil(){}


    /**
     * @Description: 提取url的在path
     * @param target 目标
     *
     * @return: 返回path
     */
    public static String getPath(String target) {

        String path = cn.hutool.core.util.URLUtil.getPath(URLUtil.normalizeURL(target));
        return path;

    }
    /**
     * @Description: 获取标准化的url
     * @param target 不标准的url
     *
     * @return:
     */
    public static String normalizeURL(String target){
        if (!target.endsWith("/")){
            target = target + "/";
        }
//        System.out.println("normalizeURL target -> " + target);
        return cn.hutool.core.util.URLUtil.normalize(target);
    }

    public static String encodeURL(String target){
        return cn.hutool.core.util.URLUtil.encode(target);
    }

    public static String getROOT(String target) {
        String[] result = target.split("/");
        String res = "";
        int i = 0;
        for (String p:result){
            if (p.equals("")){
                p = "//";
                i += 1;
            }
//            System.out.println(p);
            res += p;
            i += 1;
//            System.out.println(res + " " + i);
//            System.out.println(i);
            if (i == 4){
                return res + "/";
            }
        }
        return res + "/";
    }

    public static String getHost(String target){
        String result = null;
        URL url = null;
        try {
            url = new URL(URLUtil.normalizeURL(target));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        result = url.getHost();

//        System.out.println("getROOT result -> " + result);
        return result;
    }

    public static int getPort(String target){
//        int result ;
        URL url = null;
        try {
            url = new URL(URLUtil.normalizeURL(target));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        String protocol = url.getProtocol();
//        System.out.println(protocol);
        if (protocol.equals("https")){
            return 443;
        }else if(protocol.equals("http")){
            return 80;
        }

        return url.getPort();
    }


    public static void main(String[] args) {
        String url = "http://smartms.zihome.com/actuator/env";
        String point = "sad";

//        System.out.println(URLUtil.normalizeURL(url)+point);
//        System.out.println(URLUtil.getHost(URLUtil.normalizeURL(url)));
        System.out.println(URLUtil.getROOT(url));
//        System.out.println(URLUtil.getPort(url));
//        System.out.println(URLUtil.getPath(url));
    }




}
