package node

import (
	"context"
	"fmt"
	"gateway/common"
	client "go.etcd.io/etcd/client/v3"
	"log"
	"time"
)

// Register 注册服务
func (n *Node) Register(serverCode string, serverPort string, serverIp ...string) (func(), error) {
	return n.RegisterWithContext(context.Background(), serverCode, serverPort, serverIp...)
}

// RegisterWithContext 注册服务
func (n *Node) RegisterWithContext(ctx context.Context, serverCode string, serverPort string, domain ...string) (func(), error) {
	var err error
	var serverAddr string

	if len(domain) > 0 {
		serverAddr = domain[0]
	} else {
		ip, err := common.GetLocalIP()
		if err != nil {
			return nil, err
		}
		serverAddr = fmt.Sprintf("http://%s", ip)
	}
	//创建租约
	lease, err := n.Client.Grant(ctx, 5)
	if err != nil {
		return nil, err
	}
	//像etcd注册服务
	finalAddr := serverAddr
	if serverPort != "" {
		finalAddr = fmt.Sprintf("%s:%s", serverAddr, serverPort)
	}
	key := createServerRegisterKey(n.scheme, serverCode, finalAddr)
	_, err = n.Client.Put(ctx, key, time.Now().Format(""), client.WithLease(lease.ID))
	if err != nil {
		return nil, err
	}
	log.Println(ctx, "service registed gateway for %s success!\n", key)
	//续租约
	keepAlive, err := n.Client.KeepAlive(ctx, lease.ID)
	if err != nil {
		return nil, err
	}
	go func() {
		for {
			<-keepAlive
		}
	}()
	return func() {
		_, _ = n.Client.Revoke(ctx, lease.ID)
	}, nil
}
