package com.wisedu.coeus.util;

import java.io.File;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.helper.ApplicationHelper;

public class IPAddressUtils {
    private static DatabaseReader reader = null;
    private static final Logger LOGGER = LoggerFactory.getLogger(IPAddressUtils.class);

    static {
        File database = new File(ApplicationHelper.getWebRootPath().concat("/WEB-INF/ip/GeoLite2-City.mmdb"));
        try {
            reader = new DatabaseReader.Builder(database).build();
        } catch (Exception e) {

        }
    }

    public static Map<String, String> parse(String ip) {
        Map<String, String> map = new HashMap<String, String>();

        try {
            CityResponse city = reader.city(InetAddress.getByName(ip));
            String country = city.getCountry().getNames().get("zh-CN");
            map.put("country", country);
            map.put("province", city.getMostSpecificSubdivision().getNames().get("zh-CN"));
            if ("台湾".indexOf(country)>-1 || "香港".indexOf(country)>-1 || "澳门".indexOf(country)>-1){
            	map.put("country", "中国");
                map.put("province", country);
            }
            map.put("city", city.getCity().getNames().get("zh-CN"));
        } catch (Exception e) {
        	LOGGER.error(e.getMessage(), e);
        }

        return map;
    }

    public static String getClientIP(HttpServletRequest request) {
        String ip = Strings.trimToEmpty(request.getHeader("x-forwarded-for"));
        if (ip.isEmpty()) {
            ip = request.getRemoteAddr();
        }

        String[] ips = ip.split(",");

        if (ips != null && ips.length > 1) {
            int j = 0;
            for (int i = 0; i < ips.length; i ++) {
                ips[i] = Strings.trimToEmpty(ips[i]);
                if (ips[i].startsWith("10.") || ips[i].startsWith("127.") || ips[i].startsWith("192.")) {
                    continue;
                }
                j = i;
                break;
            }
            ip = ips[j].trim();
        }


        return ip;
    }

    

}
