package ui

import (
	"fmt"
	"go_dreamfactory/cmd/v2/lib/common"
	os_storage "go_dreamfactory/cmd/v2/lib/storage"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	"net"
	"runtime"
	"strings"
	"sync"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/go-ping/ping"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
)

type portStatus struct {
	port int
	err  string
}
type appPing struct {
	appAdapter
	resultCh chan portStatus
}

func (this *appPing) LazyInit(ptService service.PttService, obs observer.Observer) error {
	this.tabItem = container.NewTabItemWithIcon(common.TOOLBAR_PING, theme.DownloadIcon(), nil)

	content := container.NewMax()
	content.Objects = []fyne.CanvasObject{}

	targetHost := widget.NewEntry()
	targetHost.PlaceHolder = "目标主机Ip"
	//load
	storage, _ := os_storage.NewOSStorage()
	conf, err := storage.LoadConfig()
	if err != nil {
		return err
	}

	portEntry := widget.NewMultiLineEntry()
	portEntry.Text = "20,21,22,80,1521,2379,2380,3306,6379,8080,8020,8500,9000,9090,13306,50070,27019,10013,8300,8301,8600,10012,10011"
	saveBtn := widget.NewButton("保存配置", func() {
		pingConf := &os_storage.PingConf{
			Host:  targetHost.Text,
			Ports: portEntry.Text,
		}
		conf.PingConf = pingConf
		if err := storage.StoreConfig(conf); err != nil {
			logrus.WithField("err", err).Debug("保存配置")
			return
		}
	})

	form := widget.NewForm(
		widget.NewFormItem("主机", targetHost),
		widget.NewFormItem("端口", container.NewBorder(nil, nil, nil, saveBtn, portEntry)),
	)

	if conf.PingConf != nil {
		targetHost.SetText(conf.PingConf.Host)
		portEntry.SetText(conf.PingConf.Ports)
	}
	// result
	result := widget.NewMultiLineEntry()
	result.Disable()

	//初始化端口对应说明字典
	portDesc := map[int]string{
		7891:  "websocket",
		10013: "MongoDB",
		10011: "Redis",
		10012: "Consul",
		9567:  "gateway",
		9568:  "mainte",
		9569:  "worker",
		9897:  "battle",
		8001:  "cross_mainte",
		9570:  "cross_worker",
		8000:  "web",
		9571:  "cross_web",
	}

	form.OnSubmit = func() {
		result.Text = ""
		if portEntry.Text == "" {
			return
		}
		this.resultCh = make(chan portStatus)
		ports := strings.Split(portEntry.Text, ",")

		pinger, err := ping.NewPinger(targetHost.Text)
		if err != nil {
			panic(err)
		}
		pinger.Count = 3
		if runtime.GOOS == "windows" {
			pinger.SetPrivileged(true)
		}
		var msgs []string
		pinger.OnRecv = func(p *ping.Packet) {
			msgs = append(msgs, fmt.Sprintf("来自:%s 的回复 字节=%d 时间=%dms TTL=%d",
				p.IPAddr.String(),
				p.Nbytes,
				p.Rtt.Milliseconds(),
				p.Ttl))
			result.Text = strings.Join(msgs, "\n")
			result.Refresh()
		}

		if err := pinger.Run(); err != nil {
			logrus.Error(err)
		}

		ip, err := net.ResolveIPAddr("ip", targetHost.Text)
		if err != nil {
			logrus.Error(err)
			return
		}
		this.ping(ip.String(), ports)

		for p := range this.resultCh {
			desc, ok := portDesc[p.port]
			if !ok {
				desc = "未知"
			}
			msgs = append(msgs, fmt.Sprintf("%s 端口:%d %s", desc, p.port, p.err))
			result.Text = strings.Join(msgs, "\n")
			result.Refresh()
		}
	}
	form.Items[1].HintText = "多个端口使用英文,号分隔"
	form.SubmitText = "Ping"

	result.OnChanged = func(s string) {
		result.Refresh()
	}
	content.Objects = append(content.Objects, container.NewBorder(form, nil, nil, nil, result))
	this.tabItem.Content = content
	return nil
}

func (this *appPing) ping(targetHost string, ports []string) {
	var wg sync.WaitGroup
	wg.Add(len(ports))
	for _, port := range ports {
		go func(p int) {
			defer wg.Done()
			_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", targetHost, p), time.Millisecond*500)
			var errStr string
			if err == nil {
				errStr = "OK"
			} else {
				errStr = "ERR"
				logrus.Error(err)
			}
			this.resultCh <- portStatus{port: p, err: errStr}
		}(cast.ToInt(port))
	}

	go func() {
		defer close(this.resultCh)
		wg.Wait()
	}()
}

func (a *appPing) GetAppName() string {
	return common.TOOLBAR_PING
}

func (a *appPing) Icon() fyne.Resource {
	return theme.ComputerIcon()
}
