package quant.rich.emoney.pojo.dto;

import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain=true)
public class IpInfo {
    private String ip = "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) this.ip = ip.trim();
        return this;
    }

    public IpInfo setIpv6(String ipv6) {
        if (ipv6 != null) this.ipv6 = ipv6.trim();
        return this;
    }
    
    public String toString() {
        
        StringBuilder sb = new StringBuilder();
        sb.append("IP: ").append(getIp());
        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(getSubdivision())) {
                sb.append(getSubdivision());
            }
            if (StringUtils.isNotBlank(getCity()) && !Objects.equals(getCountry(), getCity())) {
                // 有时候国家和地区与城市一致的，忽略
                sb.append(getCity());
            }
        }
        else {
            sb.append("未知位置");
        }
        return sb.toString();
    }
    
    public boolean isEmpty() {
        return StringUtils.isBlank(getIp());
    }
}
