package hook

import (
	"github.com/gorilla/websocket"
	"github.com/imroc/req/v3"
	"net/url"
	"time"
)

type Hook struct {
	ServerIp     string
	AdminPort    string
	WxPort       string
	Client       *req.Client
	WorkPhoneUrl string
	Ctype        uint64
}

func NewHook(serverIp string, adminPort string, WxPort string) *Hook {

	client := req.C().DevMode()
	client.SetCommonRetryCount(2).
		SetCommonRetryBackoffInterval(1*time.Second, 5*time.Second).
		SetCommonRetryFixedInterval(2 * time.Second).SetTimeout(30 * time.Second)

	workPhoneUrl := url.URL{Scheme: "ws", Host: "chat.gkscrm.com:13088"}

	return &Hook{
		ServerIp:     serverIp,
		AdminPort:    adminPort,
		WxPort:       WxPort,
		Client:       req.C().DevMode(),
		WorkPhoneUrl: workPhoneUrl.String(),
		Ctype:        1,
	}
}

// NewWecomHook 企微客户端初始化
func NewWecomHook(serverIp string, adminPort string, WxPort string) *Hook {

	client := req.C().DevMode()
	client.SetCommonRetryCount(2).
		SetCommonRetryBackoffInterval(1*time.Second, 5*time.Second).
		SetCommonRetryFixedInterval(2 * time.Second).SetTimeout(30 * time.Second)

	wecomUrl := url.URL{Scheme: "ws", Host: "wecom.gkscrm.com:15088"}

	return &Hook{
		ServerIp:     serverIp,
		AdminPort:    adminPort,
		WxPort:       WxPort,
		Client:       req.C().DevMode(),
		WorkPhoneUrl: wecomUrl.String(),
		Ctype:        3,
	}
}

func (h *Hook) setServerIp(ip string) *Hook {
	h.ServerIp = ip
	return h
}

func (h *Hook) setAdminPort(port string) *Hook {
	h.AdminPort = port
	return h
}

func (h *Hook) setWxPort(port string) *Hook {
	h.WxPort = port
	return h
}

func (h *Hook) connWorkPhone() (*websocket.Conn, error) {
	dialer := websocket.DefaultDialer
	conn, _, err := dialer.Dial(h.WorkPhoneUrl, nil)
	if err != nil {
		return nil, err
	}
	return conn, nil
}