/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"encoding/json"
	"os"

	"github.com/jedib0t/go-pretty/v6/table"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"mortons.site/tps/internal/client"
	"mortons.site/tps/internal/properties"
)

var filter string

// listCmd represents the list command
var listCmd = &cobra.Command{
	Use:    "list",
	Short:  "Get Properties from the Tenant Properties Service (TPS)",
	Long:   `Get Properties from the Tenant Properties Service (TPS) that have been created or updated.`,
	PreRun: toggleDebug,
	RunE: func(cmd *cobra.Command, args []string) error {

		hostname := viper.GetString("hostname")
		username := viper.GetString("username")
		password := viper.GetString("password")
		clientId := viper.GetString("clientId")

		collectionJSON, err := client.GetProperties(&client.Config{Hostname: hostname, Username: username, Password: password, ClientID: clientId}, filter)
		if err != nil {
			return err
		}
		var collection properties.Collection

		if err := json.Unmarshal([]byte(collectionJSON), &collection); err != nil {
			return err
		}

		t := table.NewWriter()
		t.SetOutputMirror(os.Stdout)
		t.AppendHeader(table.Row{"Property Name", "Value", "Last Modified By", "Last Modified Date"})
		for _, p := range collection.Member {
			t.AppendRow([]interface{}{p.Name, truncateText(p.Value, 80), p.LastModifiedBy, p.LastModifiedDate})
		}
		t.Render()

		return nil
	},
}

func truncateText(s string, max int) string {
	if max > len(s) {
		return s
	}
	return s[:max] + "... (truncated) "
}

func init() {
	rootCmd.AddCommand(listCmd)

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// listCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	listCmd.Flags().StringVarP(&filter, "filter", "f", "", "Filter properties using a query. For example --fitler \"redaction\"")
}
