package ru.yandex.wmconsole.util;

import ru.yandex.wmconsole.data.MainMirrorStateEnum;
import ru.yandex.wmtools.common.Constants;

/**
 * @author avhaliullin
 */
public class WwwUtil {
    public static final String WWW_PREFIX = "www.";

    public static String switchWWW(String hostName) {
        if (hostName.contains(Constants.SCHEME_DELIMITER)) {
            if (hostName.toLowerCase().contains(Constants.SCHEME_DELIMITER + WWW_PREFIX)) {
                return hostName.replace(Constants.SCHEME_DELIMITER + WWW_PREFIX, Constants.SCHEME_DELIMITER);
            } else {
                return hostName.replace(Constants.SCHEME_DELIMITER, Constants.SCHEME_DELIMITER + WWW_PREFIX);
            }
        } else {
            if (hostName.toLowerCase().startsWith(WWW_PREFIX)) {
                return hostName.substring(WWW_PREFIX.length());
            } else {
                return WWW_PREFIX + hostName;
            }
        }
    }

    public static boolean isWWW(String hostName) {
        hostName = hostName.toLowerCase();
        return hostName.startsWith(WWW_PREFIX) || hostName.contains(Constants.SCHEME_DELIMITER + WWW_PREFIX);
    }

    public static boolean isItRight(String hostName, MainMirrorStateEnum state) {
        return isWWW(hostName) ^ MainMirrorStateEnum.WITHOUT_WWW.equals(state);
    }

    public static String getHostName(String hostName, MainMirrorStateEnum state) {
        switch (state) {
            case WITH_WWW: {
                return isWWW(hostName) ? hostName : switchWWW(hostName);
            }
            case WITHOUT_WWW: {
                return isWWW(hostName) ? switchWWW(hostName) : hostName;
            }
            default: {
                return hostName;
            }
        }
    }

    public static boolean equalsIgnoreWww(String host1, String host2) {
        return host1.equalsIgnoreCase(host2) || host1.equalsIgnoreCase(switchWWW(host2));
    }
}
