package shortUrlMgr

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

	"goutil/securityUtil"
	"goutil/stringUtil"
	"goutil/webUtil"
)

var (
	ShortUrl_SERVICE_URL = "http://a.app366.com/get"
)

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

	// 响应结果的数据
	Data string
}

// 获取短链
// appId: 为应用分配的唯一标识
// appSecret: 为应用分配的密钥
// fullUrl: 完整的Url
// timeout:超时时间（单位：秒）
// 返回值：
// ipInfoObj: IP地址信息对象
// err: 错误对象
func GetShortUrl(appId, appSecret, fullUrl string, timeout int) (shortUrl string, err error) {
	timeStamp := fmt.Sprintf("%d", time.Now().Unix())
	fullUrl = stringUtil.Base64Encode(fullUrl)
	rawString := fmt.Sprintf("AppId=%s&FullUrl=%s&Timestamp=%s&AppSecret=%s", appId, fullUrl, timeStamp, appSecret)
	sign := securityUtil.Md5String(rawString, true)

	postData := make(map[string]string, 5)
	postData["AppId"] = appId
	postData["FullUrl"] = fullUrl
	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(ShortUrl_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
	}

	shortUrl = queryResponseObj.Data

	return
}
