package graylog

import (
	"encoding/json"
	"fmt"
	"github.com/robertkowalski/graylog-golang"
	"miads/adslib"
	"miads/adslib/utils"
	"net/url"
	"time"
)
var grayLog  *gelf.Gelf

func init() {
	grayLog = gelf.New(gelf.Config{
		GraylogPort:     62001,
		GraylogHostname: "172.18.138.7",
		Connection:      "wan",
		MaxChunkSizeWan: 42,
		MaxChunkSizeLan: 1337,
	})
}

func Log(log interface{}) {
	logStr, _ := json.Marshal(log)
	fmt.Printf("graylog: %s\n", logStr)
	grayLog.Log(string(logStr))
}

func LogApi(shortMsg string, desc string, extraDesc string, reqSource string) {
	grayLogData := struct {
		ShortMessage string `json:"short_message"`
		ReqSource string `json:"req_source"`
		AdsDetail string `json:"ads_detail"`
		AdsExtraDetail string `json:"ads_extra_detail"`
	}{
		ShortMessage: shortMsg,
		ReqSource:    reqSource,
		AdsDetail: desc,
		AdsExtraDetail: extraDesc,
	}
	Log(grayLogData)
}

// 发送返回日志
func ReportGrayLog(req adslib.Request, dsp utils.DspParam, uid int, jsonFlag int) {
	gelfData := make(map[string]interface{}, 100)
	gelfData["short_message"] = "ads_api_log"
	gelfData["_user_id"] = uid
	gelfData["_device_id"] = req.DeviceId
	gelfData["_ip"] = dsp.Ip
	gelfData["_uri"] = req.QueryString
	gelfData["_province"]=dsp.Province
	gelfData["_city"]=dsp.City
	gelfData["_city_code"]=dsp.DspCityCode

	var reqData url.Values
	if jsonFlag == 0 {
		reqData, _ = url.ParseQuery(req.QueryString)
	} else {
		err := json.Unmarshal([]byte(req.Body), &reqData)
		if err != nil {
			fmt.Print("parse error")
		}
	}
	for k, v := range reqData {
		if k == "ip" {
			continue
		}
		gelfData["_" + k] = v
	}

	gelfData["_request"] = reqData.Encode()
	gelfData["_response"] = ""
	gelfData["_response_time"] = time.Now().UnixNano() / 1000

	Log(gelfData)
}
