package me.qwq.doghouse.pojo.bo;

import org.apache.commons.lang3.StringUtils;

import lombok.Data;
import lombok.experimental.Accessors;
import me.qwq.doghouse.util.IPUtils;

@Data
@Accessors(chain=true)
public class IpInfo {
    private String ipv4 = "Unknown";
    private String ipv6;
    private String country;
    private String subdivision;
    private String city;
    
    public static final IpInfo EMPTY = new IpInfo();
    
    
    
    public IpInfo setIp(String ip) {
        if (ip != null) ip = ip.trim();
        if (IPUtils.isIPv4(ip)) {
            this.ipv4 = ip;
        }
        else if (IPUtils.isIPv6(ip)) {
            this.ipv6 = ip;
        }
        return this;
    }
    
    public String toString() {
        
        StringBuilder sb = new StringBuilder();
        sb.append("IP: ").append(getIpv4());
        if (StringUtils.isNoneBlank(getIpv6())) {
            sb.append(", ").append("IPv6: ").append(getIpv6());
        }
        sb.append('(').append(getGeoString()).append(')');
        return sb.toString();
    }
    
    public String getString() {
        return toString();
    }
    
    public String getGeoString() {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(getCountry())) {
            // 国家
            sb.append(getCountry());
            if (StringUtils.isNotBlank(subdivision) && !StringUtils.equals(subdivision, country)) {
                // 有时候国家和地区一致的，忽略
                sb.append(subdivision);
            }
            if (StringUtils.isNotBlank(city) 
                    && !StringUtils.equals(country, city)           // 比如新加坡-新加坡
                    && !StringUtils.equals(subdivision, city)       // 比如曼谷-曼谷
                    && !StringUtils.startsWith(city, subdivision)) {// 比如北京-北京市
                // 有时候国家和地区与城市一致的，忽略
                sb.append(getCity());
            }
        }
        else {
            sb.append("未知位置");
        }
        return sb.toString();
    }
    
    public boolean isEmpty() {
        return StringUtils.isAllBlank(getIpv4(), getIpv6());
    }
}
