package api

import (
	"context"
	"time"

	apb "code.fbi.h-da.de/danet/gosdn/api/go/gosdn/rbac"
	nbi "code.fbi.h-da.de/danet/gosdn/controller/northbound/client"

	"github.com/google/uuid"
)

// CreateUsers creates users with provided data.
func CreateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.CreateUsersResponse, error) {
	userClient, err := nbi.UserClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &apb.CreateUsersRequest{
		Timestamp: time.Now().UnixNano(),
		User:      users,
	}

	return userClient.CreateUsers(ctx, r)
}

// GetUser returns one requested user found by name.
func GetUser(ctx context.Context, addr, name string, uuid uuid.UUID) (*apb.GetUserResponse, error) {
	userClient, err := nbi.UserClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &apb.GetUserRequest{
		Timestamp: time.Now().UnixNano(),
		Name:      name,
		Id:        uuid.String(),
	}

	return userClient.GetUser(ctx, r)
}

// GetAllUsers return all the available users.
func GetAllUsers(ctx context.Context, addr string) (*apb.GetUsersResponse, error) {
	userClient, err := nbi.UserClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &apb.GetUsersRequest{
		Timestamp: time.Now().UnixNano(),
	}

	return userClient.GetUsers(ctx, r)
}

// UpdateUsers updates all provided users.
func UpdateUsers(ctx context.Context, addr string, users []*apb.User) (*apb.UpdateUsersResponse, error) {
	userClient, err := nbi.UserClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &apb.UpdateUsersRequest{
		Timestamp: time.Now().UnixNano(),
		User:      users,
	}

	return userClient.UpdateUsers(ctx, r)
}

// DeleteUsers deletes all provided users.
func DeleteUsers(ctx context.Context, addr string, userNames []string) (*apb.DeleteUsersResponse, error) {
	userClient, err := nbi.UserClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &apb.DeleteUsersRequest{
		Timestamp: time.Now().UnixNano(),
		Username:  userNames,
	}

	return userClient.DeleteUsers(ctx, r)
}
