package util

import (
	MC "app.yhyue.com/moapp/jybase/common"
	"fmt"
	"net/http"
	"regexp"
	"strings"
	"time"
)

var (
	mobileReg = regexp.MustCompile("(?i)(Android|Mobile|Phone)")
)

func CheckPlatform(r *http.Request) (p string) {
	p = "PC"
	if CheckIsMobile(r) {
		if CheckWxBrowser(r) {
			p = "WX"
		} else {
			p = "APP"
		}
	}
	return
}

// 判断是否是微信访问
func CheckWxBrowser(Request *http.Request) bool {
	if strings.Index(Request.UserAgent(), "MicroMessenger") > -1 || strings.Index(Request.UserAgent(), "Wechat") > -1 {
		return true
	} else {
		return false
	}
}

// 是否是移动端
func CheckIsMobile(r *http.Request) bool {
	client := r.UserAgent()
	if mobileReg.MatchString(client) {
		return true
	}
	return false
}

func GetFlag(r *http.Request, w http.ResponseWriter, limitFlag string) (string, bool) {
	if limitFlag == "" {
		c, _ := r.Cookie("limitSearchTextFlag")
		if c != nil {
			limitFlag = c.Value
			if limitFlag == "" {
				sid, _ := r.Cookie("SESSIONID")
				limitFlag = sid.Value
				//limitFlag, _ = s.Get("limitSearchTextFlag").(string)
			}
		}
	}
	if limitFlag != "" {
		return limitFlag, true
	}
	limitFlag = MC.GetLetterRandom(5) + fmt.Sprint(time.Now().UnixNano())
	//s.Set("limitSearchTextFlag", limitFlag)
	c := &http.Cookie{
		Name:     "limitSearchTextFlag",
		Value:    limitFlag,
		Path:     "/",
		HttpOnly: false,
		MaxAge:   2592000, //一个月
	}
	http.SetCookie(w, c)
	return limitFlag, false
}
