package controller

import (
	"encoding/json"
	"fmt"
	"time"

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

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

// Telnet 终端
//
// GET /telnet?hostId=1
func (s *WSController) Telnet(c *gin.Context) {
	language := reqctx.AcceptLanguage(c)
	var query struct {
		HostId int64 `form:"hostId" binding:"required"` // 连接主机ID
		Cols   int   `form:"cols"`                      // 终端单行字符数
		Rows   int   `form:"rows"`                      // 终端显示行数
	}
	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
	}
	if query.Cols < 120 || query.Cols > 400 {
		query.Cols = 120
	}
	if query.Rows < 128 || query.Rows > 1200 {
		query.Rows = 128
	}

	// 登录用户信息
	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 != "telnet" {
		// 没有可访问主机信息数据！
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData")))
		return
	}

	// 创建链接Telnet客户端
	var connTelnet telnet.ConnTelnet
	neHost.CopyTo(&connTelnet)
	client, err := connTelnet.NewClient()
	if err != nil {
		// 连接主机失败，请检查连接参数后重试
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
		return
	}
	defer client.Close()
	// 创建Telnet客户端会话
	clientSession, err := client.NewClientSession(query.Cols, query.Rows)
	if err != nil {
		// 连接主机失败，请检查连接参数后重试
		c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
		return
	}
	defer clientSession.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, clientSession)
	go s.wsService.ClientWriteListen(wsClient)
	go s.wsService.ClientReadListen(wsClient, s.wsReceiveService.Telnet)

	// 实时读取Telnet消息直接输出
	msTicker := time.NewTicker(100 * time.Millisecond)
	defer msTicker.Stop()
	for {
		select {
		case ms := <-msTicker.C:
			outputByte := clientSession.Read()
			if len(outputByte) > 0 {
				outputStr := string(outputByte)
				msgByte, _ := json.Marshal(resp.Ok(map[string]any{
					"requestId": fmt.Sprintf("telnet_%d_%d", neHost.ID, ms.UnixMilli()),
					"data":      outputStr,
				}))
				wsClient.MsgChan <- msgByte

				// 退出telnet登录
				// if strings.LastIndex(outputStr, "logout\r\n") != -1 {
				// 	time.Sleep(1 * time.Second)
				// 	s.wsService.CloseClient(wsClient.ID)
				// 	return
				// }
			}
		case <-wsClient.StopChan: // 等待停止信号
			s.wsService.ClientClose(wsClient.ID)
			logger.Infof("ws Stop Client UID %d", wsClient.BindUid)
			return
		}
	}
}
