package mmlclient

import (
	"bufio"
	"fmt"
	"io"
	"net"
	"time"

	"nms_nbi/lib/core/conf"
)

// 定义MMLClient结构体
type MMLClient struct {
	awaitTime time.Duration // 等待时间
	conn      net.Conn
	reader    *bufio.Reader
	size      int // 包含字符
}

// 封装NewMMLClient函数，用于创建MMLClient实例
// 网元UDM的IP地址 "198.51.100.1"
func NewMMLClient(ip string) (*MMLClient, error) {
	// 创建TCP连接
	portMML := conf.Get("mml.port").(int)
	hostMML := fmt.Sprintf("%s:%d", ip, portMML)
	conn, err := net.Dial("tcp", hostMML)
	if err != nil {
		return nil, err
	}

	// 进行登录
	usernameMML := conf.Get("mml.user").(string)
	passwordMML := conf.Get("mml.password").(string)
	fmt.Fprintln(conn, usernameMML)
	fmt.Fprintln(conn, passwordMML)

	// 发送后等待
	awaitTime := time.Duration(300) * time.Millisecond
	time.Sleep(awaitTime)

	// 读取内容
	buf := make([]byte, 1024*1024*1)
	n, err := conn.Read(buf)
	if err != nil {
		return nil, err
	}

	// 创建MMLClient实例
	client := &MMLClient{
		conn:      conn,
		reader:    bufio.NewReader(conn),
		awaitTime: awaitTime,
		size:      n,
	}

	return client, nil
}

// 封装Send函数，用于向TCP连接发送数据
func (c *MMLClient) Send(msg string) error {
	_, err := fmt.Fprintln(c.conn, msg)
	if err != nil {
		return err
	}
	time.Sleep(c.awaitTime)
	return nil
}

// 封装Receive函数，用于从TCP连接中接收数据
func (c *MMLClient) Receive() (string, error) {
	buf := make([]byte, 1024*1024*1)
	n, err := c.reader.Read(buf)
	if err != nil {
		if err == io.EOF {
			return "", fmt.Errorf("server closed the connection")
		}
		return "", err
	}
	c.size += n
	return string(buf[0:n]), nil
}

// 封装Close函数，用于关闭TCP连接
func (c *MMLClient) Close() error {
	return c.conn.Close()
}
