package com.house365.web.util;


import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLConnection;

/**
 * 请求来源,获取请求来源IP
 */
public class RequestFromUtil {

    public static boolean  isMobileDevice(String requestHeader){
        /**
         * android : 所有android设备
         * mac os : iphone ipad
         * windows phone:Nokia等windows系统的手机
         */
        String[] deviceArray = new String[]{"android","Android","mac os","iPhone","iPad","windows phone"};
        if(requestHeader == null)
            return false;
        requestHeader = requestHeader.toLowerCase();
        for(int i=0;i<deviceArray.length;i++){
            if(requestHeader.indexOf(deviceArray[i])>0){
                return true;
            }
        }
        return false;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getAddressByIP(){
        try{
            String strIP = "192.168.110.84";
            URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while((line = reader.readLine()) != null)
            {
                result.append(line);
            }
            reader.close();
            strIP = result.substring(result.indexOf( "该IP所在地为：" ));
            strIP = strIP.substring(strIP.indexOf( "：") + 1);
            String province = strIP.substring(6, strIP.indexOf("省"));
            String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));
            return city;
        }catch( IOException e){
            return "读取失败";
        }
    }


    public static void main(String[] args){
        try
        {
            String strIP = "192.168.110.84";
            URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while((line = reader.readLine()) != null)
            {
                result.append(line);
            }
            reader.close();
            strIP = result.substring(result.indexOf( "该IP所在地为：" ));
            strIP = strIP.substring(strIP.indexOf( "：") + 1);
            String province = strIP.substring(6, strIP.indexOf("省"));
            String city = strIP.substring(strIP.indexOf("省") + 1, strIP.indexOf("市"));
//            return city;
        }catch( IOException e){
            e.printStackTrace();
//            return "读取失败";
        }
    }


//    public static String getCityInfo(String ip){
//
//        //db
//        String dbPath = IPUtil.class.getResource("/ip2region.db").getPath();
//
//        File file = new File(dbPath);
//        if ( file.exists() == false ) {
//            System.out.println("Error: Invalid ip2region.db file");
//        }
//
//        //查询算法
//        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
//        //DbSearcher.BINARY_ALGORITHM //Binary
//        //DbSearcher.MEMORY_ALGORITYM //Memory
//        try {
//            DbConfig config = new DbConfig();
//            DbSearcher searcher = new DbSearcher(config, dbPath);
//
//            //define the method
//            Method method = null;
//            switch ( algorithm )
//            {
//                case DbSearcher.BTREE_ALGORITHM:
//                    method = searcher.getClass().getMethod("btreeSearch", String.class);
//                    break;
//                case DbSearcher.BINARY_ALGORITHM:
//                    method = searcher.getClass().getMethod("binarySearch", String.class);
//                    break;
//                case DbSearcher.MEMORY_ALGORITYM:
//                    method = searcher.getClass().getMethod("memorySearch", String.class);
//                    break;
//            }
//
//            DataBlock dataBlock = null;
//            if ( Util.isIpAddress(ip) == false ) {
//                System.out.println("Error: Invalid ip address");
//            }
//
//            dataBlock  = (DataBlock) method.invoke(searcher, ip);
//
//            return dataBlock.getRegion();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return null;
//    }


}
