// Recipe "read-object": an object's latest version and its properties as typed values.
//
// Usage: go run ./recipes/read_object [object ID, default 437] [object type, default 0 (document)]
package main

import (
	"context"
	"fmt"

	"github.com/M-Files/mfiles-grpc-api-samples/mfilesclient"
	"github.com/M-Files/mfiles-grpc-api-samples/recipes/internal/recipe"
	"github.com/M-Files/mfiles-grpc-api/go/mfiles"
)

func main() {
	recipe.Main(run)
}

func run(ctx context.Context) error {
	id := recipe.IntArg(0, 437)
	objectType := recipe.IntArg(1, 0)
	client, err := recipe.Connect(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// [START read-object]
	// Property names, by ID. A real application caches these (they change rarely).
	propertyDefs := mfiles.NewIRPCPropertyDefsClient(client.Conn)
	defs, err := propertyDefs.GetPropertyDefs(ctx, &mfiles.GetPropertyDefsRequest{})
	if err != nil {
		return err
	}
	names := map[int32]string{}
	for _, def := range defs.GetPropertyDefs() {
		names[def.GetId()] = def.GetName()
	}

	// The latest version and its properties in one call.
	objects := mfiles.NewIRPCObjectOperationsClient(client.Conn)
	response, err := objects.GetObjectInfoAndProperties(ctx,
		&mfiles.GetObjectInfoAndPropertiesRequest{
			ObjId:         mfilesclient.ObjID(objectType, id),
			LatestVersion: true,
		})
	if err != nil {
		return err
	}

	fmt.Println(recipe.Describe(response.GetObjectInfo()))
	for _, property := range response.GetPropertyArray() {
		name, ok := names[property.GetPropertyDef()]
		if !ok {
			name = "?"
		}
		fmt.Printf("  %s (%d): %s\n", name, property.GetPropertyDef(),
			recipe.FormatValue(property.GetValue()))
	}
	// [END read-object]
	return nil
}
