package controller

import (
	"fmt"
	"path/filepath"
	"runtime"

	"be.ems/src/framework/i18n"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	traceService "be.ems/src/modules/trace/service"

	"github.com/gin-gonic/gin"
)

// 实例化控制层 PacketController 结构体
var NewPacket = &PacketController{
	packetService: traceService.NewPacket,
}

// 信令跟踪
//
// PATH /trace/packet
type PacketController struct {
	packetService *traceService.Packet // 信令跟踪服务
}

// 信令跟踪网卡设备列表
//
// GET /devices
func (s *PacketController) Devices(c *gin.Context) {
	data := s.packetService.NetworkDevices()
	c.JSON(200, resp.OkData(data))
}

// 信令跟踪开始
//
// POST /start
func (s *PacketController) Start(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		TaskNo     string `json:"taskNo" binding:"required"` // 任务编号
		Device     string `json:"device" binding:"required"` // 网卡设备
		Filter     string `json:"filter" `                   // 过滤表达式（port 33030 or 33040）
		OutputPCAP bool   `json:"outputPCAP" `               // 输出PCAP文件 （默认false）
	}
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	msg, err := s.packetService.LiveStart(body.TaskNo, body.Device, body.Filter, body.OutputPCAP)
	if err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, resp.OkData(msg))
}

// 信令跟踪结束
//
// POST /stop
func (s *PacketController) Stop(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		TaskNo string `json:"taskNo" binding:"required"` // 任务编号
	}
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	if err := s.packetService.LiveStop(body.TaskNo); err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, resp.Ok(nil))
}

// 信令跟踪过滤
//
// PUT /filter
func (s *PacketController) Filter(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		TaskNo string `json:"taskNo" binding:"required"` // 任务编号
		Expr   string `json:"expr" `                     // 过滤表达式（port 33030 or 33040）
	}
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	if err := s.packetService.LiveFilter(body.TaskNo, body.Expr); err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, resp.Ok(nil))
}

// 信令跟踪续期保活
//
// PUT /keep-alive
func (s *PacketController) KeepAlive(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var body struct {
		TaskNo   string `json:"taskNo" binding:"required"` // 任务编号
		Duration int    `json:"duration" `                 // 服务失效的时间，默认设置为120秒
	}
	if err := c.ShouldBindBodyWithJSON(&body); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

	// 默认设置为120秒
	if body.Duration <= 1 {
		body.Duration = 120
	}

	if err := s.packetService.LiveTimeout(body.TaskNo, body.Duration); err != nil {
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, resp.Ok(nil))
}

// 信令跟踪文件
//
// GET /filePull
func (s *PacketController) FilePull(c *gin.Context) {
	var querys struct {
		TaskNo string `json:"taskNo" form:"taskNo" binding:"required"` // 任务编号
	}
	if err := c.ShouldBindQuery(&querys); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}
	fileName := fmt.Sprintf("%s.pcap", querys.TaskNo)
	localFilePath := filepath.Join("/usr/local/omc/packet", fileName)
	if runtime.GOOS == "windows" {
		localFilePath = fmt.Sprintf("C:%s", localFilePath)
	}
	c.FileAttachment(localFilePath, fileName)
}
