package api

import (
	"context"
	"time"

	ppb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/pnd"
	nbi "code.fbi.h-da.de/danet/gosdn/controller/northbound/client"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var dialOptions []grpc.DialOption

func init() {
	dialOptions = []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
	}
}

// Init initialises the CLI client.
func Init(ctx context.Context, addr string) error {
	resp, err := GetAllPnds(ctx, addr)
	if err != nil {
		return err
	}

	if len(resp.Pnd) > 0 {
		pid := resp.Pnd[0].Id
		viper.Set("CLI_PND", pid)
		log.Infof("PND: %v", pid)
	}

	return viper.WriteConfig()
}

// GetIds requests all UUID information from the controller.
func GetIds(ctx context.Context, addr string) ([]*ppb.PrincipalNetworkDomain, error) {
	resp, err := GetAllPnds(ctx, addr)
	if err != nil {
		return nil, err
	}
	return resp.Pnd, nil
}

// GetAllPnds requests all PNDs.
func GetAllPnds(ctx context.Context, addr string) (*ppb.GetPndListResponse, error) {
	pndClient, err := nbi.PndClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	req := &ppb.GetPndListRequest{
		Timestamp: time.Now().UnixNano(),
	}
	return pndClient.GetPndList(ctx, req)
}
