package system

import (
	"fmt"
	"io"
	"net/http"
	"xg_dba/api"

	"xg_dba/internal/global"
	system "xg_dba/internal/services/system"

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

// //获取缓存中所有连接信息
func GetSingleSystemInfo_controller(c *gin.Context) {
	//获取连接信息
	connectInfo := api.ServerInfoRequest{}
	if err := c.BindJSON(&connectInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if sysInfo, err := global.Cache.GetSingleSystemInfoCache(connectInfo.BaseFileName ,connectInfo.Host); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{"message": "success",
			"data": sysInfo,
		})
	}
}

// 设置系统信息(todo)
func SetSystemInfo_controller(c *gin.Context) {
	// 获取连接信息
	connectInfo := []api.ServerInfoRequest{}
	if err := c.BindJSON(&connectInfo); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	if connectInfo[0].BaseFileName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "BaseFileName is required"})
		return
	}
	// 创建新的进度 channel 并返回进度 ID
	progressID := global.Progress.CreateProgress()
	// 启动任务的 goroutine
	go func() {
		system.SetSystemInfo_service(connectInfo, fmt.Sprintf("./config/%s/", connectInfo[0].BaseFileName), progressID)
	}()

	// 返回给前端 progress ID
	//	c.JSON(http.StatusOK, gin.H{"progress_id": progressID})

	c.JSON(http.StatusOK, gin.H{"message": "success",
		"progressID": progressID,
	})
	// //使用 Stream 处理实时推送
	// c.Stream(func(w io.Writer) bool {
	// 	if message, ok := <-progressChan; ok {
	// 		c.SSEvent("progress", gin.H{"message": message})
	// 		fmt.Println("Progress给:", message)
	// 		return true
	// 	}
	// 	return false
	// })
}

// 设置系统信息并推送进度
func GetSystemInfoProgress_controller(c *gin.Context) {
	// 解析请求参数
	progressID := c.Query("progressID") // 获取查询参数 `id`,也就是 `progressID`
	if progressID == "" {
		c.JSON(400, gin.H{
			"error": "progressID is required",
		})
		return
	}

	// 获取对应的进度 channel
	progressChan, ok := global.Progress.GetProgressChan(progressID)
	if !ok {
		c.JSON(http.StatusNotFound, gin.H{"error": "Progress ID not found"})
		return
	}

	// //使用 Stream 处理实时推送
	c.Stream(func(w io.Writer) bool {
		if message, ok := <-progressChan; ok {
			c.SSEvent("progress", gin.H{"message": message})
			fmt.Println("Progress给:", message)
			return true
		}
		return false
	})

}