package adslib

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"miads/adslib/encrypt"
	"miads/adslib/utils"
	"net/url"
	"strings"
	"time"
)

type Request struct {
	Imei        string
	Idfa        string
	Model       string
	Brand       string
	ScreenSize  string `json:"screen_size"`
	NetworkType int `json:"network_type,string"`
	Androidid   string `json:"android_id"`
	Platform    int `json:"platform,string"`
	OsVersion   string `json:"os_version"`
	UaClient    string `json:"ua"`
	ReqSource   string `json:"req_source"`
	Mac         string `json:"mac"`
	ReqSourceIp string `json:"ip"`
	DeviceId	string `json:"device_id"`

	NewAdsFlag int64
	content    string

	RequestTime int64 `json:"-"`
	QueryString string `json:"-"`
	Body string `json:"-"`
}

func (self *Request) Parse(c *gin.Context) {
	self.RequestTime = time.Now().Unix()
	self.QueryString = c.Request.URL.RawQuery

	body, _ := c.GetRawData()
	self.Body = string(body)
	// 取了body要塞回去
	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))

	self.Imei = utils.GetArgument(c, "imei", "")
	self.Idfa = utils.GetArgument(c, "idfa", "")
	self.Model = utils.GetArgument(c, "model", "")
	self.Brand = utils.GetArgument(c, "brand", "")
	self.ScreenSize = utils.GetArgument(c, "screen_size", "")
	self.NetworkType = int(utils.GetIntArgument(c, "network_type", 3))
	self.Androidid = utils.GetArgument(c, "android_id", "")
	self.Platform = int(utils.GetIntArgument(c, "platform", 1))
	self.OsVersion = utils.GetArgument(c, "os_version", "")
	self.UaClient = utils.GetArgument(c, "ua", "")
	self.ReqSource = utils.GetArgument(c, "req_source", "")
	self.Mac = utils.GetArgument(c, "mac", "")
	self.ReqSourceIp = utils.GetArgument(c, "ip", "")
	self.DeviceId = utils.GetArgument(c, "device_id", "")

	self.NewAdsFlag = utils.GetIntArgument(c, "new_ads_flag", 0)
	self.content = utils.GetArgument(c, "ads_content", "")
	fmt.Printf("ads flag: %d, content: %s\n", self.NewAdsFlag, self.content)

	// 进行解密
	if self.NewAdsFlag == 1 && self.content != "" {
		contentDecode, err := encrypt.Decrypt(self.content, []byte(GetConf().SecretKey))
		if err != nil {
			fmt.Printf("error: %s", err)
			c.String(404, "decode failed")
			return
		}
		contentDecode = utils.Rstrip(contentDecode)
		err = json.Unmarshal([]byte(contentDecode), self)
		if err != nil {
			fmt.Println(err)
			c.String(404, "decode json body failed: %s", err)
			return
		}

		fmt.Println(contentDecode)
	}

	self.UaClient, _ = url.QueryUnescape(self.UaClient)
	self.Mac = strings.ReplaceAll(self.Mac, ":", "")
}

func (self *Request) IsMiDevice() bool {
	if strings.Index(self.Brand, "mi") != -1 ||
		strings.Index(self.Brand, "MI") != -1 ||
		strings.Index(self.Brand, "Mi") != -1 {
		return true
	}
	return false
}
