package main

import (
	_ "embed"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"time"

	"dyproxy/modules/proxy"

	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"github.com/sirupsen/logrus"
)

var (
	outTE      *walk.TextEdit
	wnd        *walk.MainWindow
	btnService *walk.PushButton
	err        error
	pr         *proxy.Proxy
)

//go:embed ca.crt
var ca []byte

func init() {
	// if go os is windows
	if strings.ToLower(os.Getenv("GOOS")) == "windows" {
		// get tmp path
		tmpPath := os.TempDir()
		// write ca.crt to tmp path
		err := os.WriteFile(tmpPath+"/ca.crt", ca, 0o644)
		if err != nil {
			logrus.Fatal(err)
		}
		logrus.Info("import root cert")
		// run certutil.exe -addstore root tmpPath+"/ca.crt"
		cmd := exec.Command("certutil.exe", "-addstore", "root", tmpPath+"/ca.crt")
		err = cmd.Run()
		if err != nil {
			logrus.Fatal(err)
		}
	}
}

func main() {
	MainWindow{
		AssignTo: &wnd,
		Title:    "粉丝代理服务",
		Size:     Size{300, 300},
		Layout:   VBox{},
		Children: []Widget{
			PushButton{
				Text:     "开启服务",
				MinSize:  Size{300, 50},
				AssignTo: &btnService,
				OnClicked: func() {
					errChan := make(chan error)
					if btnService.Text() == "开启服务" {
						btnService.SetEnabled(false)
						outTE.AppendText("服务启动中...\r\n")
						if pr == nil {
							pr = proxy.NewProxy("https://f.jdwan.com", false, 10)

							go func() {
								errChan <- pr.Serve(29999)
							}()
						}
						select {
						case err := <-errChan:
							outTE.AppendText(err.Error() + "\r\n")
						case <-time.After(2 * time.Second):
							outTE.AppendText("服务启动成功\r\n")
							btnService.SetText("停止服务")
							go func() {
								err = <-errChan
								outTE.AppendText("[ERR] " + err.Error() + "\r\n")
								btnService.SetText("开启服务")
								btnService.SetEnabled(true)
							}()
						}
						btnService.SetEnabled(true)
					} else {
						btnService.SetEnabled(false)
						outTE.AppendText("服务停止中...\r\n")
						pr.Shutdown()
						outTE.AppendText("服务停止成功\r\n")
						btnService.SetText("开启服务")
						btnService.SetEnabled(true)
					}
				},
			},
			TextEdit{AssignTo: &outTE, ReadOnly: true},
		},
	}.Create()

	wnd.Closing().Attach(func(canceled *bool, reason walk.CloseReason) {
		fmt.Println("Application closing.")
		if pr != nil {
			outTE.AppendText("服务停止中...\r\n")
			pr.Shutdown()
			outTE.AppendText("服务停止成功\r\n")
		}
	})

	wnd.Disposing().Attach(func() {
		fmt.Println("Application has exited.")
	})

	wnd.Run()
}
