package api

import (
	"dhcp/api/request"
	"dhcp/global"
	"dhcp/internal/ip"
	"dhcp/internal/service"
	"dhcp/model"
	"dhcp/result"
	"github.com/gin-gonic/gin"
)

func DHCPServerRegisterRoute(r *gin.Engine) {
	dhcpServer := r.Group("/dhcpServer")
	dhcpServer.POST("/start", DHCPServerStart)
	dhcpServer.POST("/stop", DHCPServerStop)
	dhcpServer.GET("/info", DHCPServerInfo)
	dhcpServer.GET("/localip", GetLocalIPAndInterfaces)
	dhcpServer.POST("/delete", DHCPServerDelete)
	dhcpInfo := r.Group("/dhcpInfo")
	dhcpInfo.POST("/add", AddDHCPInfo)
	dhcpInfo.GET("/get", GetDHCPInfo)
	dhcpInfo.GET("/delete", DeleteDHCPInfo)
	dhcpInfo.POST("/update", UpdateDHCPInfo)
	dhcpInfo.GET("/getByMac", GetDHCPInfoByMac)
}

func DHCPServerStart(c *gin.Context) {
	var req request.DHCPService
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, result.Result{
			Code: 400,
			Data: nil,
			Msg:  "参数错误",
		})
		return
	}
	re := service.StartDHCPService(c.Request.Context(), global.Log, req)
	c.JSON(200, re)
}

func DHCPServerDelete(c *gin.Context) {
	var req request.DHCPService
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, result.Result{
			Code: 400,
			Data: nil,
			Msg:  "参数错误",
		})
		return
	}
	re := service.DeleteDHCPService(c.Request.Context(), global.Log, req)
	c.JSON(200, re)
}

func DHCPServerStop(c *gin.Context) {
	var req request.DHCPService
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, result.Result{
			Code: 400,
			Data: nil,
			Msg:  "参数错误",
		})
		return
	}
	re := service.StopDHCPService(c.Request.Context(), global.Log, req)
	c.JSON(200, re)
}

func DHCPServerInfo(c *gin.Context) {
	var d []request.DHCPService
	for _, v := range service.DHCPServiceInfoMap {
		d = append(d, v)
	}
	c.JSON(200, result.Result{
		Code: 200,
		Data: d,
		Msg:  "获取当前服务成功",
	})
}

func GetLocalIPAndInterfaces(c *gin.Context) {
	re := ip.GetLocalIPAndInterface()
	c.JSON(200, re)
}

func AddDHCPInfo(c *gin.Context) {
	var req model.DHCP
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, result.Result{
			Code: 400,
			Data: nil,
			Msg:  "参数错误",
		})
		return
	}
	re := service.AddDHCPInfo(req)
	c.JSON(200, re)
}

func GetDHCPInfo(c *gin.Context) {
	re := service.GetDHCPInfo()
	c.JSON(200, re)
}

func DeleteDHCPInfo(c *gin.Context) {
	req := c.Query("mac")
	re := service.DeleteDHCPInfo(req)
	c.JSON(200, re)
}

func UpdateDHCPInfo(c *gin.Context) {
	var req model.DHCP
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(200, result.Result{
			Code: 400,
			Data: nil,
			Msg:  "参数错误",
		})
		return
	}
	re := service.UpdateDHCPInfo(req)
	c.JSON(200, re)
}

func GetDHCPInfoByMac(c *gin.Context) {
	req := c.Query("mac")
	re := service.GetDHCPInfoByMac(req)
	c.JSON(200, re)
}
