package middleware

import (
	"crawler/model"
	"crawler/utility"
	"fmt"
	"github.com/gin-gonic/gin"
	ua "github.com/mileusna/useragent"
	"time"
)

// 접속기록
func Access() gin.HandlerFunc {
	return func(c *gin.Context) {
		var (
			gotParam  gin.LogFormatterParams
			accessLog = new(model.AccessLogModel)
			start     = time.Now()
		)

		c.Next()

		/*
			duration := utility.GetDurationInMillseconds(start)
			log.Printf("duration: %g\n", duration)
		*/

		gin.LoggerWithConfig(gin.LoggerConfig{
			Formatter: func(param gin.LogFormatterParams) string {
				gotParam = param
				return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
					param.ClientIP,
					param.TimeStamp.Format(time.RFC1123),
					param.Method,
					param.Path,
					param.Request.Proto,
					param.StatusCode,
					param.Latency,
					param.Request.UserAgent(),
					param.ErrorMessage,
				)
			},
		})

		/*
			fmt.Printf("Request: %#v\n", gotParam.Request)
			fmt.Printf("TimeStamp: %s\n", gotParam.TimeStamp)
			fmt.Printf("StatusCode: %d\n", gotParam.StatusCode)
			fmt.Printf("Latency: %d\n", gotParam.Latency)
			fmt.Printf("ClientIP: %#v\n", gotParam.ClientIP)
			fmt.Printf("Method: %s\n", gotParam.Method)
			fmt.Printf("Path: %s\n", gotParam.Path)
			fmt.Printf("ErrorMessage: %s\n", gotParam.ErrorMessage)
		*/

		var (
			requestID    = c.Writer.Header().Get("Request-Id")
			status       = c.Writer.Status() // access the status we are sending
			referer      = c.Request.Referer()
			clientIP     = utility.GetClientIP(c)
			method       = c.Request.Method
			path         = c.Request.RequestURI
			errorMessage = gotParam.ErrorMessage
			userAgent    = c.Request.UserAgent()
			latency      = time.Since(start).Seconds() // after request
			useragent    = ua.Parse(userAgent)
		)

		/*
			fmt.Printf("RequestID: %#v\n", requestID)
			fmt.Printf("StatusCode: %d\n", statusCode)
			fmt.Printf("Referer: %s\n", referer)
			fmt.Printf("ClientIP: %#v\n", clientIP)
			fmt.Printf("Method: %s\n", method)
			fmt.Printf("Path: %s\n", path)
			fmt.Printf("ErrorMessage: %s\n", errorMessage)
			fmt.Printf("UserAgent: %s\n", userAgent)
			fmt.Printf("latency: %d\n", latency)
			fmt.Printf("status: %d\n", status)
		*/

		accessLog.RequestID = requestID
		accessLog.RequestURI = path
		accessLog.ClientIP = clientIP
		accessLog.Referer = referer
		accessLog.UserAgent = userAgent
		accessLog.Browser = useragent.Name + " / " + useragent.Version
		accessLog.Os = useragent.OS + " / " + useragent.OSVersion
		accessLog.Device = useragent.Device
		accessLog.Method = method
		accessLog.ErrorMessage = errorMessage
		accessLog.Latency = fmt.Sprint(latency)
		accessLog.Status = status
		accessLog.Save()
	}
}
