package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"iot_manager_service/util/common"
	"net/http"
	"strings"
)

type CustomResponseWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
	Host string
}

func (w CustomResponseWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	if strings.Contains(w.Host, "cloud.long-chi.com") {
		old := string(b)
		//为兼容https，此处需要修改下
		new := strings.ReplaceAll(old, "http://110.40.223.170:9000/", "https://cloud.long-chi.com/")
		new = strings.ReplaceAll(new, "http://106.52.134.22:9099/", "https://cloud.long-chi.com/")
		b = []byte(new)
	}
	return w.ResponseWriter.Write(b)
}

func (w CustomResponseWriter) WriteString(s string) (int, error) {
	w.body.WriteString(s)
	return w.ResponseWriter.WriteString(s)
}
func CheckAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//该路由下不校验token
		if strings.Contains(ctx.Request.RequestURI, "/login") ||
			strings.Contains(ctx.Request.RequestURI, "/captcha") ||
			strings.Contains(ctx.Request.RequestURI, "/tenant/info") ||
			strings.Contains(ctx.Request.RequestURI, "/api/ctwing/aep/callback") ||
			strings.Contains(ctx.Request.RequestURI, "/token") {
			ctx.Next()
			return
		}

		authorization := ctx.GetHeader(Authorization)
		if authorization != "" {
			token := ParseAccessToken(authorization)
			if token != nil {
				ctx.Set(Authorization, token)

				blw := &CustomResponseWriter{body: bytes.NewBufferString(""), ResponseWriter: ctx.Writer, Host: ctx.Request.Host}
				ctx.Writer = blw
				ctx.Next()
				return
			}
		}
		ctx.JSON(http.StatusUnauthorized, common.NormalResponse(http.StatusUnauthorized, "token is invalid", nil))
		ctx.Abort()
	}
}
