package com.agilex.vamf.utils;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * Created by guthriev on 4/15/14.
 */
public class URLUtility {

    private static final int HTTPS_DEFAULT_PORT = 443;
    private static final String HTTPS_SCHEME = "https";
    private static final int HTTP_DEFAULT_PORT = 80;

    public static URI removePort(URI uri, int portNumber) {

        if(uri.getPort() != portNumber){
            return uri;
        }

        String updatedUri = uri.toString().replaceFirst(":" + portNumber, "");

        URI urlWithNoPort = null;

        try {
            urlWithNoPort = new URI(updatedUri);
        } catch (URISyntaxException e) {
            throw new RuntimeException("Unable construct URI");
        }

        return urlWithNoPort;
    }

    public static URI removeStandardPortsFromUri(URI uri) {
        if(HTTPS_SCHEME.equalsIgnoreCase(uri.getScheme())){
            uri = URLUtility.removePort(uri, HTTPS_DEFAULT_PORT);
        }else{
            uri = URLUtility.removePort(uri, HTTP_DEFAULT_PORT);
        }

        return uri;
    }

}
