package api

import (
	"dhcp/api/request"
	"dhcp/global"
	"dhcp/internal/dhcpServer/backend"
	"dhcp/internal/ip"
	"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 := backend.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 := backend.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 := backend.StopDHCPService(c.Request.Context(), global.Log, req)
	c.JSON(200, re)
}

func DHCPServerInfo(c *gin.Context) {
	var d []request.DHCPService
	for _, v := range backend.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 := backend.AddDHCPInfo(req)
	c.JSON(200, re)
}

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

func DeleteDHCPInfo(c *gin.Context) {
	req := c.Query("mac")
	re := backend.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 := backend.UpdateDHCPInfo(req)
	c.JSON(200, re)
}

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