package com.avaya.customer.example.servlet.utils;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static org.apache.commons.lang.StringUtils.isNotEmpty;

public class Utils {

    /**
     * Method builds URL starting with "https://"
     *
     * @param parts
     * @return
     */
    public static String buildHttpSecureUrl(String... parts) {

        final String url = joinUrlParts(parts);

        // add the protocol if needed
        if (httpPattern.matcher(url).lookingAt()) {
            return httpPattern.matcher(url).replaceFirst("https://");
        } else if (httpSecurePattern.matcher(url).lookingAt()) {
            return url;
        } else {
            return "https://" + url;
        }
    }

    public static void delay(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //=================================== private ===============================================

    private static String joinUrlParts(String[] parts) {

        if (parts.length == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder(256);
        for (String part : parts) {
            if (isNotEmpty(sb.toString())) {
                sb.append("/");
            }
            sb.append(part.trim().replaceAll("(\\\\|/)+$", "").replaceAll("^(\\\\|/)+", ""));
        }

        return sb.toString();
    }

    private static final Pattern httpPattern = Pattern.compile("^http://", Pattern.CASE_INSENSITIVE);
    private static final Pattern httpSecurePattern = Pattern.compile("^https://", Pattern.CASE_INSENSITIVE);
}
