package controller

import (
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/redis"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/framework/vo/result"
	neService "be.ems/src/modules/network_element/service"

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

// Redis 终端
//
// GET /redis?hostId=1
func (s *WSController) Redis(c *gin.Context) {
	language := ctx.AcceptLanguage(c)
	var query struct {
		HostId string `form:"hostId" binding:"required"` // 连接主机ID
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
		return
	}

	// 登录用户信息
	loginUser, err := ctx.LoginUser(c)
	if err != nil {
		c.JSON(401, result.CodeMsg(401, i18n.TKey(language, err.Error())))
		return
	}

	neHost := neService.NewNeHost.SelectById(query.HostId)
	if neHost.HostID != query.HostId || neHost.HostType != "redis" {
		// 没有可访问主机信息数据！
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.noData")))
		return
	}

	// 创建链接Redis客户端
	var connRedis redis.ConnRedis
	neHost.CopyTo(&connRedis)
	client, err := connRedis.NewClient()
	if err != nil {
		// 连接主机失败，请检查连接参数后重试
		c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
		return
	}
	defer client.Close()

	// 将 HTTP 连接升级为 WebSocket 连接
	wsConn := s.wsService.UpgraderWs(c.Writer, c.Request)
	if wsConn == nil {
		return
	}
	defer wsConn.Close()

	wsClient := s.wsService.ClientCreate(loginUser.UserID, nil, wsConn, client)
	go s.wsService.ClientWriteListen(wsClient)
	go s.wsService.ClientReadListen(wsClient, s.wsReceiveService.Redis)

	// 等待停止信号
	for value := range wsClient.StopChan {
		s.wsService.ClientClose(wsClient.ID)
		logger.Infof("ws Stop Client UID %s %s", wsClient.BindUid, value)
		return
	}
}
