package api

import (
	"context"
	"time"

	pb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/core"
	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 := GetAllCore(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 := GetAllCore(ctx, addr)
	if err != nil {
		return nil, err
	}
	return resp.Pnd, nil
}

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