package ru.yandex.webmaster.common.util;

import java.net.IDN;

import org.apache.commons.lang.StringUtils;

import ru.yandex.webmaster.common.util.HostnamePart;

/**
 * @author aherman
 */
public class HostnamePartUtils {
    public static final String HTTP = "http://";
    public static final String HTTPS = "https://";

    public static HostnamePart cleanHostnamePart(String hostnamePartStr) {
        if (StringUtils.isEmpty(hostnamePartStr)) {
            return null;
        }
        boolean isIDN = false;
        boolean isPrefix = false;
        HostnamePart.Protocol protocol = HostnamePart.Protocol.HTTP;

        hostnamePartStr = hostnamePartStr.toLowerCase();

        StringBuilder sb = new StringBuilder(hostnamePartStr.length());
        int i = 0;
        if (hostnamePartStr.startsWith(HTTP)) {
            i = HTTP.length();
            isPrefix = true;
        }

        if (hostnamePartStr.startsWith(HTTPS)) {
            i = HTTPS.length();
            isPrefix = true;
            protocol = HostnamePart.Protocol.HTTPS;
        }

        for (; i < hostnamePartStr.length(); i++) {
            char ch = hostnamePartStr.charAt(i);
            if (Character.isLetterOrDigit(ch)) {
                sb.append(ch);
            } else if (ch == '-' || ch == '_' || ch == '.') {
                sb.append(ch);
            }
        }
        String result = StringUtils.trimToNull(sb.toString());
        if (result == null) {
            return null;
        }
        isIDN = !result.equals(IDN.toASCII(result));

        return new HostnamePart(protocol, result, isPrefix, isIDN);
    }
}
