package controller

import (
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/vo/result"
	neService "be.ems/src/modules/network_element/service"
	traceService "be.ems/src/modules/trace/service"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 实例化控制层 TCPdumpController 结构体
var NewTCPdump = &TCPdumpController{
	tcpdumpService: traceService.NewTCPdump,
	neInfoService:  neService.NewNeInfo,
}

// 信令抓包
//
// PATH /tcpdump
type TCPdumpController struct {
	tcpdumpService *traceService.TCPdump // 信令抓包服务
	neInfoService  *neService.NeInfo     // 网元信息服务
}

// 网元抓包PACP 开始
//
// POST /start
func (s *TCPdumpController) DumpStart(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		NeType string `json:"neType" binding:"required"` // 网元类型
		NeId   string `json:"neId" binding:"required"`   // 网元ID
		Cmd    string `json:"cmd" binding:"required"`    // 命令 "-n -s 0 -v"
	}
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	taskCode, err := s.tcpdumpService.DumpStart(body.NeType, body.NeId, body.Cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, result.OkData(taskCode))
}

// 网元抓包PACP 结束
//
// POST /stop
func (s *TCPdumpController) DumpStop(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		NeType   string `json:"neType" binding:"required"`   // 网元类型
		NeId     string `json:"neId" binding:"required"`     // 网元ID
		TaskCode string `json:"taskCode" binding:"required"` // 任务码，停止任务并查看日志信息
	}
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	logFiles, err := s.tcpdumpService.DumpStop(body.NeType, body.NeId, body.TaskCode)
	if err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, result.OkData(logFiles))
}

// UPF标准版内部抓包
//
// POST /upf
func (s *TCPdumpController) UPFTrace(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var body struct {
		NeType string `json:"neType" binding:"required"` // 网元类型
		NeId   string `json:"neId" binding:"required"`   // 网元ID
		Cmd    string `json:"cmd" binding:"required"`    // 命令
	}
	err := c.ShouldBindBodyWith(&body, binding.JSON)
	if err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	msg, err := s.tcpdumpService.UPFTrace(body.NeType, body.NeId, body.Cmd)
	if err != nil {
		c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
		return
	}
	c.JSON(200, result.OkData(msg))
}
