package controller

import (
	"fmt"

	"be.ems/src/framework/database/redis"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/reqctx"
	"be.ems/src/framework/resp"
	neService "be.ems/src/modules/ne/service"

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

// Redis 终端
//
// GET /redis?hostId=1
func (s *WSController) Redis(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		HostId int64 `form:"hostId" binding:"required"` // 连接主机ID
	}
	if err := c.ShouldBindQuery(&query); err != nil {
		errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
		c.JSON(422, resp.CodeMsg(resp.CODE_PARAM_PARSER, errMsgs))
		return
	}

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

	neHost := neService.NewNeHost.FindById(query.HostId)
	if neHost.ID != query.HostId || neHost.HostType != "redis" {
		// 没有可访问主机信息数据！
		c.JSON(200, resp.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, resp.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 %d %s", wsClient.BindUid, value)
		return
	}
}
