package ipMgr

import (
	"encoding/json"
	"fmt"
	"time"

	"goutil/securityUtil"
	"goutil/webUtil"
)

var (
	IP_SERVICE_URL = "http://ipip.7qule.com/query"
)

// 服务器的响应对象
type QueryResponse struct {
	// 响应结果的状态值
	ResultStatus string

	// 响应结果的数据
	Data *IPInfo
}

// IP信息对象
type IPInfo struct {
	// 所属大陆块
	Continent string

	// 国家
	Country string

	// 省份
	Region string

	// 城市
	City string

	// 网络服务提供商
	Isp string
}

// 查询ip地址的详细信息
// appId: 为应用分配的唯一标识
// appSecret: 为应用分配的密钥
// ip: 待查询的ip地址
// isDomestic: 是否为国内的IP
// timeout:超时时间（单位：秒）
// 返回值：
// ipInfoObj: IP地址信息对象
// err: 错误对象
func Query(appId, appSecret, ip string, isDomestic bool, timeout int) (ipInfoObj *IPInfo, err error) {
	timeStamp := fmt.Sprintf("%d", time.Now().Unix())
	rawString := fmt.Sprintf("AppId=%s&IP=%s&Timestamp=%s&AppSecret=%s", appId, ip, timeStamp, appSecret)
	sign := securityUtil.Md5String(rawString, true)

	postData := make(map[string]string, 5)
	postData["AppId"] = appId
	postData["IP"] = ip
	postData["IsDomestic"] = fmt.Sprintf("%t", isDomestic)
	postData["Timestamp"] = timeStamp
	postData["Sign"] = sign

	header := webUtil.GetFormHeader()
	transport := webUtil.NewTransport()
	transport.DisableKeepAlives = true
	transport = webUtil.GetTimeoutTransport(transport, timeout)

	statusCode, result, err := webUtil.PostMapData(IP_SERVICE_URL, postData, header, transport)
	//statusCode, result, err := webUtil.PostMapData(IP_SERVICE_URL, postData, header, transport)
	if err != nil {
		return
	}
	if statusCode != 200 {
		err = fmt.Errorf("StatusCode:%d is wrong.", statusCode)
		return
	}

	var queryResponseObj *QueryResponse
	err = json.Unmarshal(result, &queryResponseObj)
	if err != nil {
		return
	}

	if queryResponseObj.ResultStatus != "" {
		err = fmt.Errorf("Query result:%s", queryResponseObj.ResultStatus)
		return
	}

	ipInfoObj = queryResponseObj.Data

	return
}
