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"
)

// GetChanges requests all pending and unconfirmed changes from the controller
func GetChanges(ctx context.Context, addr, pnd string) (*ppb.GetChangeListResponse, error) {
	client, err := nbi.PndClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	req := &ppb.GetChangeListRequest{
		Timestamp: time.Now().UnixNano(),
		Pid:       pnd,
	}
	return client.GetChangeList(ctx, req)
}

// Commit sends a Commit request for one or multiple changes to the
// controller.
func Commit(ctx context.Context, addr, pnd string, cuids ...string) (*ppb.SetChangeListResponse, error) {
	changes := make([]*ppb.SetChange, len(cuids))
	for i, arg := range cuids {
		changes[i] = &ppb.SetChange{
			Cuid: arg,
			Op:   ppb.Operation_OPERATION_COMMIT,
		}
	}
	return CommitConfirm(ctx, addr, pnd, changes)
}

// Confirm sends a Confirm request for one or multiple changes to the
// controller
func Confirm(ctx context.Context, addr, pnd string, cuids ...string) (*ppb.SetChangeListResponse, error) {
	changes := make([]*ppb.SetChange, len(cuids))
	for i, arg := range cuids {
		changes[i] = &ppb.SetChange{
			Cuid: arg,
			Op:   ppb.Operation_OPERATION_CONFIRM,
		}
	}
	return CommitConfirm(ctx, addr, pnd, changes)
}

// CommitConfirm confirms a commit
func CommitConfirm(ctx context.Context, addr, pnd string, changes []*ppb.SetChange) (*ppb.SetChangeListResponse, error) {
	client, err := nbi.PndClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}
	req := &ppb.SetChangeListRequest{
		Timestamp: time.Now().UnixNano(),
		Change:    changes,
		Pid:       pnd,
	}
	return client.SetChangeList(ctx, req)
}

// ChangeRequest change creates a ChangeRequest for the specified OND. ApiOperations are
// used to specify the type of the change (update, replace, delete as specified
// in https://github.com/openconfig/reference/blob/master/rpc/gnmi/gnmi-specification.md#34-modifying-state)
// For delete operations the value field needs to contain an empty string.
func ChangeRequest(ctx context.Context, addr, did, pid, path, value string, op ppb.ApiOperation) (*ppb.SetPathListResponse, error) {
	req := &ppb.ChangeRequest{
		Did:   did,
		Path:  path,
		Value: value,
		ApiOp: op,
	}
	return SendChangeRequest(ctx, addr, pid, req)
}

// SendChangeRequest sends a change request
func SendChangeRequest(ctx context.Context, addr, pid string, req *ppb.ChangeRequest) (*ppb.SetPathListResponse, error) {
	pndClient, err := nbi.PndClient(addr, dialOptions...)
	if err != nil {
		return nil, err
	}

	r := &ppb.SetPathListRequest{
		Timestamp:     time.Now().UnixNano(),
		ChangeRequest: []*ppb.ChangeRequest{req},
		Pid:           pid,
	}
	return pndClient.SetPathList(ctx, r)
}