package middleware

import (
	"github.com/labstack/echo/v4"
	//"time"
	"io"
	"os"

	"github.com/sirupsen/logrus"
	//"http/net"
	//"pastebin_backend/app/controller"
)

func Auth(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		mylogger(c)
		uid := getUid(c)
		c.Set("uid", uid)
		return next(c)
	}
}

type logInfo struct {
	User_Agent string
	IP         string
	time       string
	path       string
}

/*
向文件或 stdout 输出详细的日志，记录用户的 User-Agent、IP 地址、访问时间、访问路径等信息
User-Agent,访问路径,暂且无法实现
*/
func mylogger(c echo.Context) {
	//c.GET("User-Agent")
	//userAgent := controller.Ctx.Request.Header.Get("User-Agent")
	ip := echo.ExtractIPDirect()(c.Request())

	//日志输出文件
	file, err := os.OpenFile("files/sys.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		logrus.Fatalln("Faild to open error logger file:", err)
	}
	//同时写文件和屏幕
	fileAndStdoutWriter := io.MultiWriter(os.Stdout, file)
	logrus.SetOutput(fileAndStdoutWriter)
	logrus.WithField("ip", ip).Info("info log")
}

// 检测 uid 是否有效
func isUidValid(uid string) bool {
	if uid == "" {
		return false
	}
	return true
}

// 从报文中获得uid,给新用户分配uid
func getUid(c echo.Context) interface{} {
	cookie, err := c.Cookie("User")
	if err != nil || !isUidValid(cookie.Value) {
		logrus.Println("uid invalid,分配新uid")
		return 114514
	} else {
		return cookie.Value
	}
}
