package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	client "iaun.cn/linux/services/client"
	service "iaun.cn/linux/services/test"
	"log"
	"strconv"
	"sync"
	"time"
)

var wg sync.WaitGroup
var id string

const (
	clientAddress = "192.168.226.133:30001"
)

func test(a int) {
	defer wg.Done()
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	conn, err := grpc.DialContext(ctx, clientAddress, grpc.WithBlock(), grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect:%v", err)
		return
	}
	defer func() { _ = conn.Close() }()
	c := service.NewGreeterClient(conn)

	r, err := c.SayHello(ctx, &service.HelloRequest{Name: "test" + strconv.Itoa(a)})
	if err != nil {
		log.Fatalf("could not send data:%v", err)
		return
	}
	fmt.Println(r.GetMessage())
}

func loop(addr string, secret string) {
	t := time.NewTimer(time.Second * 5)
	for {
		now := time.Now().Unix()
		server := &client.Server{
			Id:        id,
			Secret:    secret,
			Timestamp: now,
		}
		a, b := sendInit(addr, server)
		fmt.Println(a)
		fmt.Println(b)
		a, b = sendMemory(addr, server)
		fmt.Println(a)
		fmt.Println(b)
		a, b = sendNetIO(addr, server)
		fmt.Println(a)
		fmt.Println(b)
		a, b = sendCPUPercent(addr, server)
		fmt.Println(a)
		fmt.Println(b)
		<-t.C
		t.Reset(time.Second * 5)
	}
}

func main() {
	conf, err := getConfig()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	addr := fmt.Sprintf("%s:%d", conf.Server, conf.Port)
	fmt.Println(addr)
	id, err = getId()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	loop(addr, conf.Secret)
}
