package com.qmth.boot.tools.matcher;

import org.apache.commons.lang3.StringUtils;

/**
 * IP地址匹配工具
 * 模版格式举例：192.168.*.0，其中*为通配符
 * 若模版或IP地址空白或为NULL，则匹配失败
 */
public class IPMatcher {

    public static final char FUZZY_PLACEHOLDER = '*';

    public static final char SECTION_SPLIT = '.';

    public static boolean match(String pattern, String ip) {
        pattern = StringUtils.trimToNull(pattern);
        ip = StringUtils.trimToNull(ip);
        if (pattern == null || ip == null) {
            return false;
        }
        int i1 = 0;
        int i2 = 0;
        int l1 = pattern.length();
        int l2 = ip.length();
        while (i1 < l1 && i2 < l2) {
            char c1 = pattern.charAt(i1);
            char c2 = ip.charAt(i2);
            if (c1 == SECTION_SPLIT) {
                i1++;
                continue;
            } else if (c2 == SECTION_SPLIT) {
                i2++;
                continue;
            } else if (c1 == FUZZY_PLACEHOLDER) {
                i1 = pattern.indexOf(SECTION_SPLIT, i1);
                i2 = ip.indexOf(SECTION_SPLIT, i2);
                if (i1 < 0) {
                    i1 = l1;
                }
                if (i2 < 0) {
                    i2 = l2;
                }
                continue;
            }
            if (c1 != c2) {
                return false;
            } else {
                i1++;
                i2++;
            }
        }
        return i1 == l1 && i2 == l2;
    }

    public static void main(String[] args) {
        System.out.println(match("192.168.0.*", "192.168.2.10"));
    }

}
