package tui

import (
	"bufio"
	"fmt"
	"gitee.ltd/lxh/logger/log"
	"github.com/charmbracelet/bubbles/table"
	"github.com/charmbracelet/lipgloss"
	"github.com/spf13/cast"
	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
	"os"
	"strings"
	"wireguard-ui/http/vo"
	"wireguard-ui/model"
	"wireguard-ui/service"
	"wireguard-ui/utils"
)

var BaseStyle = lipgloss.NewStyle().
	BorderStyle(lipgloss.NormalBorder()).
	BorderForeground(lipgloss.Color("240"))

var menus = []string{"[1] 客户端链接列表", "[2] 客户端", "[3] 服务端", "[4] 设置", "[q] 退出"}

// PrintMenu
// @description: 打印一下菜单
func PrintMenu() {
	fmt.Println("\n菜单:")
	for _, menu := range menus {
		fmt.Println(menu)
	}
}

// GenerateTable
// @description: 生成数据表
// @param column
// @param rows
// @return string
func GenerateTable(column []table.Column, rows [][]string) string {
	var data []table.Row
	for _, v := range rows {
		data = append(data, v)
	}

	tl := table.New(
		table.WithColumns(column),
		table.WithRows(data),
		table.WithHeight(len(data)+1),
	)

	s := table.DefaultStyles()
	s.Header = s.Header.
		BorderStyle(lipgloss.NormalBorder()).
		BorderForeground(lipgloss.Color("240")).
		BorderBottom(true).
		Bold(false)
	s.Selected = lipgloss.NewStyle()

	tl.SetStyles(s)

	return BaseStyle.Render(tl.View()+"\n") + "\n一共有 【" + fmt.Sprintf("%d", len(data)) + "】 条数据"
}

// GenerateIP
// @description: 生成IP
// @return clientIPS
// @return serverIPS
// @return err
func GenerateIP() (clientIPS, serverIPS []string, err error) {
	// 获取一下服务端信息，因为IP分配需要根据服务端的IP制定
	serverInfo, err := service.Setting().GetWGServerForConfig()
	if err != nil {
		return nil, nil, err
	}

	var assignIPS []string
	// 只获取最新的一个
	var clientInfo *model.Client
	if err = service.Client().Order("created_at DESC").Take(&clientInfo).Error; err == nil {
		// 遍历每一个ip是否可允许再分配
		for _, ip := range strings.Split(clientInfo.IpAllocation, ",") {
			if cast.ToInt64(utils.Network().GetIPSuffix(ip)) >= 255 {
				log.Errorf("IP：[%s]已无法分配新IP", ip)
				continue
			} else {
				assignIPS = append(assignIPS, ip)
			}
		}
	}

	ips := utils.Network().GenerateIPByIPS(serverInfo.Address, assignIPS...)

	return ips, serverInfo.Address, nil
}

// GenerateKeys
// @description: 生成密钥对
// @return keys
// @return err
func GenerateKeys() (keys *vo.Keys, err error) {
	// 为空，新增
	privateKey, err := wgtypes.GeneratePrivateKey()
	if err != nil {
		return nil, err
	}
	publicKey := privateKey.PublicKey().String()
	presharedKey, err := wgtypes.GenerateKey()
	if err != nil {
		return nil, fmt.Errorf("生成预共享密钥失败: %s", err.Error())
	}
	keys = &vo.Keys{
		PrivateKey:   privateKey.String(),
		PublicKey:    publicKey,
		PresharedKey: presharedKey.String(),
	}

	return keys, nil
}

// Show
// @description: 展示
// @param data
func Show(data any) {
	fmt.Println(data)
}

// readInput
// @description: 读取输入
// @param prompt
// @return string
func readInput(prompt string) string {
	fmt.Print(prompt)
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	return scanner.Text()
}
