package utils

import (
	"applet/pkg/pb"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"strconv"
	"time"
)

func GetBusinessIntClient(url, port string) pb.BusinessIntClient {
	target := fmt.Sprintf("%s:%s", url, port)
	conn, err := grpc.Dial(target, grpc.WithInsecure())
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return pb.NewBusinessIntClient(conn)
}

func GetBusinessExtClient(url, port string) pb.BusinessExtClient {
	target := fmt.Sprintf("%s:%s", url, port)
	conn, err := grpc.Dial(target, grpc.WithInsecure())
	//defer conn.Close()
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return pb.NewBusinessExtClient(conn)
}

func GetLogicExtClient(url, port string) pb.LogicExtClient {
	target := fmt.Sprintf("%s:%s", url, port)
	conn, err := grpc.Dial(target, grpc.WithInsecure())
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return pb.NewLogicExtClient(conn)
}

func GetCtx(token, userId, deviceId, masterId string) context.Context {
	if userId == "" {
		userId = "1"
	}
	if deviceId == "" {
		deviceId = "1"
	}
	if token == "" {
		token = "0"
	}
	return metadata.NewOutgoingContext(context.TODO(), metadata.Pairs(
		"user_id", userId,
		"device_id", deviceId,
		"token", token,
		"master_id", masterId,
		"request_id", strconv.FormatInt(time.Now().UnixNano(), 10)))
}
