package main

import (
	"context"
	"fmt"

	lxdCmd "github.com/canonical/lxd/shared/cmd"
	"github.com/canonical/microcluster/v2/microcluster"
	"github.com/spf13/cobra"

	"github.com/canonical/microceph/microceph/api/types"
	"github.com/canonical/microceph/microceph/client"
)

type cmdClusterConfigGet struct {
	common        *CmdControl
	cluster       *cmdCluster
	clusterConfig *cmdClusterConfig
}

func (c *cmdClusterConfigGet) Command() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "get <key>",
		Short: "Get specified Ceph Cluster config",
		RunE:  c.Run,
	}

	return cmd
}

func (c *cmdClusterConfigGet) Run(cmd *cobra.Command, args []string) error {
	// Get can be called with a single key.
	if len(args) != 1 {
		return cmd.Help()
	}

	m, err := microcluster.App(microcluster.Args{StateDir: c.common.FlagStateDir})
	if err != nil {
		return fmt.Errorf("unable to configure MicroCeph: %w", err)
	}

	cli, err := m.LocalClient()
	if err != nil {
		return err
	}

	req := &types.Config{
		Key: args[0],
	}

	configs, err := client.GetConfig(context.Background(), cli, req)
	if err != nil {
		return err
	}

	data := make([][]string, len(configs))
	for i, config := range configs {
		data[i] = []string{fmt.Sprintf("%d", i), config.Key, config.Value}
	}

	header := []string{"#", "Key", "Value"}
	err = lxdCmd.RenderTable(lxdCmd.TableFormatTable, header, data, configs)
	if err != nil {
		return err
	}

	return nil
}
