package node

import (
	"app.yhyue.com/moapp/jybase/iputil"
	"context"
	"fmt"
	client "go.etcd.io/etcd/client/v3"
	"log"
	"time"
)

// Register 注册服务
func (n *Node) Register(serverCode string, serverPort string, serverIp ...string) (func(), error) {
	stop, err := NewPublisher(serverCode, serverPort, n.Client.Endpoints()...).Register()
	if err != nil {
		return nil, err
	}
	return func() {
		stop <- struct{}{}
	}, nil
	//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 {
		serverAddr = fmt.Sprintf("http://%s", iputil.InternalIp())
	}
	//创建租约
	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.Printf("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 {
			select {
			case <-n.Client.Ctx().Done():
				fmt.Println("server closed")
				return
			case _, ok := <-keepAlive:
				if !ok {
					fmt.Println("keep live channel closed")
					_, _ = n.Client.Revoke(ctx, lease.ID)
					return
				}
			}
		}
	}()
	return func() {
		_, _ = n.Client.Revoke(ctx, lease.ID)
	}, nil
}
